#include "CenterMatchLogic.h"
#include "StringConverter.h"
#include "ResourceManager.h"
#include "Database/DatabaseEnv.h"
#include "StringConverter.h"
#include "json/json.h"
#include "NGLog.h"
#include "Character.h"
#include "CharManager.h"
#include "Items.h"
#include "ItemManager.h"
#include "Users.h"
#include "UserManager.h"
#include "Channels.h"
#include "ChannelManager.h"
#include "Towns.h"
#include "TownManager.h"
#include "ItemModelManager.h"
#include "Message.h"
#include "CenterBankManager.h"
#include "VipCardManager.h"
#include "Tools.h"
#include "XMLData.h"
#include "GameDefine.h"
#include XMLDATA_MGR_PATH
#include LOGIC_MGR_PATH
#include LOG_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include "OpcodesEx.h"
#include "WorldPacket.h"
#include "AIInterface.h"
#include "WSSocketManager.h"
#include "json/json.h"
#include "ProtocolDealEnums.h"
#include "url.h"
#include "CRUsersManager.h"
#include "DataTransferManager.h"
#include "CenterMatchManager.h"
#include "String.h"
#include "CenterMatchLogManager.h"
//#include "CenterMatchManager.h"
using namespace AIScript;
CenterMatchLogic::CenterMatchLogic()
{
	m_cm_id = 0;
	m_MatchMode = 0;
	m_agent_id = 0;
	m_NowLoop = 0;
	m_MatchStatus = enCenterMatchStatus_Pre;
	m_MatchStageStatus = enCenterMatchStageStatus_Default;
	m_bFinals = false;
	m_join_code = "";
	m_gz_id = 0;
	m_matchStartWaitTimer = 0;
	m_matchEndTimer = 0;
	m_matchStageEndWaitTimer = 0;
	m_from_gz_id = 0;
	m_StageLoop = 0;
	updateTimer = now();
	m_robotLeaveTimer = time(0);
}

CenterMatchLogic::~CenterMatchLogic()
{
	MatchEnd();
}



CenterMatchLogic::CenterMatchLogic(CenterMatch  cm)
{
	m_MatchStageStatus = enCenterMatchStageStatus_Default;
	m_matchRiseUpWaitTimer = 0;
	m_matchStartWaitTimer = 0;
	m_cm_id = cm.cm_id;
	m_join_code = cm.join_code;
	m_MatchMode = cm.match_mode;
	m_NowLoop = cm.data1;
	m_MatchBeginTime = cm.start_time;
	m_MatchLimit_Time = cm.limit_time;
	m_MatchStatus = enCenterMatchStatus_Pre;
	m_each_loop = cm.each_loop;
	m_NextRoundNum = cm.enter_limit_num;
	m_gz_id = cm.gz_id;
	m_agent_id = cm.reg_from;
	m_bFinals = false;
	m_matchEndTimer = 0;
	m_matchStageEndWaitTimer = 0;
	stageRule.clear();
	m_l_MatchPlayer.clear();
	m_l_MatchChannel.clear();
	m_RankList.clear();
	m_StageLoop = 0;
	m_NowStage = 1;
	m_robotLeaveTimer = time(0);
	initCenterMatchInfo(cm);
}

//解析创建规则
void CenterMatchLogic::initCenterMatchInfo(CenterMatch  cm)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata2, val);

	if (cm.match_mode == enCenterMatchMode_TaoTaiSai)
	{
		String rule1 = val["rule1"].asString();
		std::vector<String> vals = StringUtil::split(rule1, ",");
		stageRule = vals.back();
	}
	limit_time = cm.limit_time;
	stCenterMatchModeInfo  CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);
	if (m_CenterMatchStage.stageMode == 0)
	{
		m_CenterMatchStage = CenterMatchModeInfo.matchStage.front();
		if (val.isMember("loop"))
		{
			m_CenterMatchStage.channel_limit_loop = val["loop"].asInt();
		}
		
		Log.Debug("CenterMatchLogic::initCenterMatchInfo", "cm_id[%d] First Stage MatchMode[%d] CenterMatchModeInfo.matchMode[%d] stageMode[%d]", m_cm_id, m_MatchMode, CenterMatchModeInfo.matchMode, m_CenterMatchStage.stageMode);
	}
}

//创建牌桌群
bool CenterMatchLogic::CreateChannels(const uint8 & dataType)
{
	//WGS_CENTERMATCHLOGIC_LOCK

	std::map<uint32, CenterMatchChannelInfo >::iterator iter, ei = m_l_MatchChannel.end();
	uint32 channelNums = GetMatchNeedChannelNum(dataType);
	uint32 nowChannels = 0;
	for (iter = m_l_MatchChannel.begin(); iter != ei; )
	{
		if (iter->second.status == enCenterMatchChannelStatus_ended)
		{
			ChannelPtr pChannel = sChannelMgr.load(iter->second.ChannelId);
			if (pChannel.isNull() == false)
			{
				pChannel->setUInt32Field("status", 255);
				pChannel->SaveDB();
			}
			m_l_MatchChannel.erase(iter++);
			continue;
			
		}
		else if (iter->second.status == enCenterMatchChannelStatus_ready)
		{
			nowChannels++;
		}
		iter++;
	}
	//m_l_MatchChannel.clear();
	Log.Debug("CenterMatchLogic::CreateChannels", "cm_id[%d] nowChannels[%d] channelNum[%d]", m_cm_id, nowChannels,channelNums);
	if (nowChannels >= channelNums) {
		return true;
	}
	else
	{
		channelNums = channelNums - nowChannels;
	}



	Log.Debug("CenterMatchLogic::CreateChannels", "cm_id[%d] channelNum[%d]", m_cm_id, channelNums);
	for (uint16 i = 1; i <= channelNums; i++)
	{
		ChannelPtr pChan;
		uint8  tryTimes = 0;
		do
		{
			if (tryTimes > 3)
			{
				return false;
			}
			stPlayerCreateCenterBattle stPCB;
			CenterMatch cm;
			sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
			stPCB.cb_id = cm.cm_id;
			stPCB.pid = cm.pid;
			stPCB.base_coins = cm.base_coins;
			stPCB.fan_coins = cm.fan_coins;
			stPCB.coins_model = cm.coins_model;
			stPCB.init_coins = cm.init_coins;
			stPCB.think_time = cm.think_time;
			stPCB.timeout = cm.timeout;
			stPCB.battle_name = cm.battle_name;
			stPCB.limit_loop = m_CenterMatchStage.channel_limit_loop;
			stPCB.limit_time = cm.limit_time;
			stPCB.top_times = cm.top_times;
			stPCB.game_id = cm.game_id;
			stPCB.gz_id = cm.gz_id;
			stPCB.mode = cm.mode;
			stPCB.extra_data = cm.sdata2;
			pChan = CreateChannel(stPCB);

			if (pChan.isNull())
			{
				tryTimes++;
				Sleep(100);
			}

		} while (pChan.isNull());

		CenterMatchChannelInfo temp;
		temp.ChannelId = pChan->getHandle();
		temp.status = enCenterMatchChannelStatus_ready;
		temp.TableNumber = i;
		m_l_MatchChannel.insert(std::make_pair(temp.ChannelId, temp));
	}
	Log.Debug("CenterMatchLogic::CreateChannels", "cm_id[%d] m_l_MatchChannel[%d]", m_cm_id, m_l_MatchChannel.size());

	return true;
}

//创建牌桌
ChannelPtr CenterMatchLogic::CreateChannel(stPlayerCreateCenterBattle stPCB)
{
	ChannelPtr pChannel;
	Log.Debug("CenterMatchLogic::CreateCenterChannel", "game_id[%u] mode[%u] 111", stPCB.game_id, stPCB.mode);
	// 获取
	stCenterBattleMode stCBM = sXmlDataMgr.GetCenterBattleModeByGameid(stPCB.game_id, stPCB.mode);
	if (stCBM.town_id == 0)
		return pChannel;
	Log.Debug("CenterMatchLogic::CreateCenterChannel", "town_id[%u] 222", stCBM.town_id);
	TownPtr pTown = sTownMgr.getByHandle(stCBM.town_id);
	if (pTown.isNull())
		return pChannel;

	Resource * pChn = sChannelMgr.newDumyChannel();

	pChn->setUInt32Field("ai", pTown->getUInt32Field("ai"));
	pChn->setUInt32Field("town_id", pTown->getHandle());

	Vector3 pos = sRegionMgr.getWorldRondomPosition();
	pChn->setFloatField("x", pos.x);
	pChn->setFloatField("y", pos.y);
	pChn->setFloatField("z", pos.z);

	//uint32 check_count;


	//pChn->setStringField("winner", strCode.c_str());	// 进入验证码
	pChn->setUInt32Field("type", 101);					// 组局类型65
	pChn->setUInt32Field("status", 1);					// 牌桌状态
	pChn->setUInt32Field("server_id", sRegionMgr.getServerID());
	pChn->setUInt32Field("world_server_id", sRegionMgr.getServerID());
	pChn->setUInt32Field("create_time", time(0));		// 创建时间
	pChn->setUInt32Field("march_id", stPCB.cb_id);
	// info字段以json格式写入牌桌对应参数
	Json::Value val;

	val["fz_pid"] = stPCB.pid;					// 房主PID
	val["cm_id"] = stPCB.cb_id;					// 组局ID
	val["jd_id"] = m_NowStage;					// 阶段id
	val["base_coins"] = stPCB.base_coins;		// 底分
	val["fan_coins"] = stPCB.fan_coins;			// 翻分
	val["coins_model"] = stPCB.coins_model;		// 游戏用货币类型
	val["init_coins"] = stPCB.init_coins;		// 进入房间限制（初始带入货币数量）
	val["think_time"] = stPCB.think_time;		// 考虑时间
	val["timeout"] = stPCB.timeout;				// 超时时间
	val["battle_name"] = stPCB.battle_name;		// 房间名称
	val["limit_loop"] = stPCB.limit_loop;		// 局数限制
	val["limit_time"] = stPCB.limit_time;		// 时间限制
	val["top_times"] = stPCB.top_times;			// 封顶翻数配置
	val["game_id"] = stPCB.game_id;				// 游戏ID
	val["gz_id"] = stPCB.gz_id;					// 游戏分区ID
	val["mode"] = stPCB.mode;					// 游戏模式
	val["match_start_time"] = m_matchStartWaitTimer;

	Json::Value valExtra;
	Json::Reader reader;
	reader.parse(stPCB.extra_data, valExtra);
	
	if (valExtra.size())
	{
		if (valExtra.isMember("extra_data"))
		{
			val["extra_data"] = valExtra["extra_data"];
			if (val["extra_data"].empty())
			{
				val["extra_data"]["cm_id"] = m_cm_id;
			}
		}
		else
			val["extra_data"]["cm_id"] = m_cm_id;
		if (valExtra.isMember("pay_mode"))
		{
			val["pay_mode"] = valExtra["pay_mode"];
		}
		else
			val["pay_mode"] = 1;
		if (valExtra.isMember("matchType"))
		{
			val["matchType"] = valExtra["matchType"];
		}
		else
			val["matchType"] = 0;
		if (valExtra.isMember("duijufei"))
		{
			val["duijufei"] = valExtra["duijufei"];
		}
		else
		{
			Json::Value temp;
			temp["msId"] = 0;
			temp["num"] = 0;
			val["duijufei"] = temp;
		}
		//for (Json::Value::iterator iterV = valExtra.begin(); iterV != valExtra.end(); ++iterV)
		//{// 游戏玩法json节点复制
		//	if ((*iterV).isString())
		//		val["extra_data"][iterV.key().asString()] = (*iterV).asString();
		//	else
		//		val["extra_data"][iterV.key().asString()] = (*iterV).asUInt();
		//}
	}


	Json::FastWriter w;
	Log.Debug("CenterMatchLogic::CreateCenterChannel", "val[%s]", w.write(val).c_str());
	pChn->setStringField("info", w.write(val));				//组局数据相关配置

	pChannel = sChannelMgr.loadChannelDatabase(pChn);
	sChannelMgr.freeDumyChannel(pChn);

	return pChannel;
}

//将玩家分配到牌桌
bool CenterMatchLogic::AssignedToChannel()
{
	//WGS_CENTERMATCHLOGIC_LOCK;


	SwitzerlandShiftOrder();

	return false;
}

//更新牌桌信息
bool CenterMatchLogic::UpdateCenterMatchChannelData(const uint32 & channel_id)
{
	//WGS_CENTERMATCHLOGIC_LOCK;


	if (m_l_MatchChannel.find(channel_id) == m_l_MatchChannel.end()) return false;

	ChannelPtr pChannel = sChannelMgr.load(channel_id);

	if (pChannel.isNull())  return false;

	CenterMatchChannelInfo * pChannelInfo = &m_l_MatchChannel[channel_id];
	pChannelInfo->battle_times++;
	//pChannelInfo->eliminate = m_CenterMatchStage.eliminate;
	//pChannelInfo->base_score = m_CenterMatchStage.base_score;

	/*Json::Value val;
	Json::Reader reader;

	reader.parse(pChannel->getStringField("info"), val);*/

	/*if (val.isMember("base_coins"))
	{
		val["base_coins"] = pChannelInfo->base_score;
	}
	if (val.isMember("eliminate_coins"))
	{
		val["eliminate_coins"] = pChannelInfo->base_score;
	}*/

	//pChannel->setStringField("info", Json::FastWriter().write(val));

	return true;
}

//更新玩家信息
bool CenterMatchLogic::UpdateCenterMatchPlayerData(CenterMatchTotalLog & cmtt)
{
	Log.Debug("CenterMatchLogic::UpdateCenterMatchPlayerData", "cmtt.cm_id[%d] m_cm_id[%d] cmtt.channel_id[%d]", cmtt.cm_id, m_cm_id, cmtt.channel_id);
	if (cmtt.cm_id != m_cm_id)return false;

	if (m_l_MatchChannel.find(cmtt.channel_id) == m_l_MatchChannel.end())return false;

	CenterMatchChannelInfo * pChannelInfo = &m_l_MatchChannel[cmtt.channel_id];

	for (uint32 i = 0; i < pChannelInfo->PlayerList.size(); i++)
	{
		if (m_l_MatchPlayer.find(pChannelInfo->PlayerList[i]) == m_l_MatchPlayer.end())
			continue;
		uint32 char_id = pChannelInfo->PlayerList[i];
		for (uint8 j = 0; j < cmtt.list.size(); j++)
		{
			CMPIter iter = m_l_MatchPlayer.find(char_id);
			Log.Debug("CenterMatchLogic::UpdateCenterMatchPlayerData", "cmtt.cm_id[%d] cmtt.list[%d].char_id[%d] iter!= ei[%d]", cmtt.cm_id, j, cmtt.list[j].char_id, iter != m_l_MatchPlayer.end());
			if (cmtt.list[j].char_id == char_id)
			{
				m_l_MatchPlayer[char_id].score += cmtt.list[j].winLose;
				Json::Value val;
				Json::Reader reader;
				reader.parse(m_l_MatchPlayer[char_id].data1, val);

				if (val.isMember("server_data") == false)
				{
					val["server_data"]["battle_count"] = 1;
					val["server_data"]["battle_win"] = 0;
					val["json_data"]["胜利次数"] = 0;
					val["json_data"]["失败次数"] = 0;
				}
				else
				{
					val["server_data"]["battle_count"] = val["server_data"]["battle_count"].asInt() + 1;
				}
				val["json_data"]["总场次"] = val["server_data"]["battle_count"].asInt();
				if (cmtt.list[j].winLose > 0)
				{
					val["server_data"]["battle_win"] = val["server_data"]["battle_win"].asInt() + 1;
					val["json_data"]["胜利次数"] = val["server_data"]["battle_win"].asInt();
				}
				else
				{
					val["json_data"]["失败次数"] = val["server_data"]["battle_count"].asInt() - val["server_data"]["battle_win"].asInt();
				}
				CharPtr pChr = sCharMgr.load(char_id);
				if (val.isMember("name") == false)
				{
					val["name"] = string_url_encode(pChr->getStringField("name"));
				}
				if (val.isMember("desc") == false)
				{
					val["desc"] = string_url_encode(pChr->getStringField("desc"));
				}
				m_l_MatchPlayer[char_id].data1 = Json::FastWriter().write(val);
				if (m_l_MatchPlayer[char_id].best_score < m_l_MatchPlayer[char_id].score)
				{
					m_l_MatchPlayer[char_id].best_score = m_l_MatchPlayer[char_id].score;
				}
				if (m_l_MatchPlayer[char_id].lowest_score > m_l_MatchPlayer[char_id].score)
				{
					m_l_MatchPlayer[char_id].lowest_score = m_l_MatchPlayer[char_id].score;
				}
				break;

			}
		}
	}


	return false;
}

//获取玩家信息
CenterMatchPlayerInfo CenterMatchLogic::GetCenterMatchPlayerInfo(const uint32 & char_id)
{
	CenterMatchPlayerInfo temp;
	if (m_l_MatchPlayer.find(char_id) != m_l_MatchPlayer.end())
	{
		temp = m_l_MatchPlayer[char_id];
	}
	return temp;
}

//发送牌桌中的比赛信息 
void CenterMatchLogic::SendCenterMatchChannelMatchInfo(CenterMatchTotalLog & cmtt)
{
	std::map<uint32, CenterMatchPlayerInfo> temp;
	CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
	for (uint32 i = 0; i < cmtt.list.size(); i++)
	{
		if (m_l_MatchPlayer.find(cmtt.list[i].char_id) != m_l_MatchPlayer.end())
		{
			CenterMatchPlayerInfo cmpi = m_l_MatchPlayer.find(cmtt.list[i].char_id)->second;
			temp[cmpi.char_id] = cmpi;
		}
	}
	for (uint32 i = 0; i < cmtt.list.size(); i++)
	{
		CharPtr pChr = sCharMgr.load(cmtt.list[i].char_id);
		WorldPacket packet;
		if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}
	std::map<uint32,CenterMatchChannelInfo>::iterator iter = m_l_MatchChannel.find(cmtt.channel_id);
	if (iter != m_l_MatchChannel.end())
	{
		for (uint32 i = 0; i < iter->second.WatchPlayerList.size(); i++)
		{
			CharPtr pChr = sCharMgr.getByHandle(iter->second.WatchPlayerList[i]);
			if (m_vWatchList.find(pChr->getHandle()) == m_vWatchList.end()) continue;
			WorldPacket packet;
			if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
		}
	}

}

//发送牌桌中的比赛信息 
void CenterMatchLogic::SendCenterMatchChannelMatchInfo(CharPtr pChr)
{
	std::map<uint32, CenterMatchPlayerInfo> temp;
	CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
	if (m_l_MatchPlayer.find(pChr->getHandle()) == m_l_MatchPlayer.end())
	{
		if (m_vWatchList.find(pChr->getHandle()) == m_vWatchList.end()) return;
		
		
		if (m_l_MatchChannel.find(m_vWatchList[pChr->getHandle()]) != m_l_MatchChannel.end())
		{
			CenterMatchChannelInfo cmci = m_l_MatchChannel.find(m_vWatchList[pChr->getHandle()])->second;
			std::map<uint32, CenterMatchPlayerInfo> temp;
			CenterMatch cm;
			sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
			for (uint32 i = 0; i < cmci.PlayerList.size(); i++)
			{
				if (m_l_MatchPlayer.find(cmci.PlayerList[i]) != m_l_MatchPlayer.end())
				{
					CenterMatchPlayerInfo cmpi = m_l_MatchPlayer.find(cmci.PlayerList[i])->second;
					temp[cmpi.char_id] = cmpi;
				}
			}
			WorldPacket packet;
			if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
			if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
				sGLMgr.SendProtocolsToChr(pChr, &packet);

		}
		return;
	}
	CenterMatchPlayerInfo cmpi = m_l_MatchPlayer.find(pChr->getHandle())->second;
	Log.Debug("CenterMatchLogic::SendCenterMatchChannelMatchInfo", "m_cm_id[%d] char[%d] cmpi.now_Channel[%d]", m_cm_id, pChr->getHandle(), cmpi.now_Channel);
	if (m_l_MatchChannel.find(cmpi.now_Channel) == m_l_MatchChannel.end()) return;
	CenterMatchChannelInfo cmci = m_l_MatchChannel.find(cmpi.now_Channel)->second;
	Log.Debug("CenterMatchLogic::SendCenterMatchChannelMatchInfo", "m_cm_id[%d] cmci.PlayerList.size[%d]", m_cm_id, cmci.PlayerList.size());
	for (uint32 i = 0; i < cmci.PlayerList.size(); i++)
	{
		if (m_l_MatchPlayer.find(cmci.PlayerList[i]) != m_l_MatchPlayer.end())
		{
			CenterMatchPlayerInfo cmpi = m_l_MatchPlayer.find(cmci.PlayerList[i])->second;
			temp[cmpi.char_id] = cmpi;
		}
	}

	WorldPacket packet;
	if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
		sGLMgr.SendProtocolsToChr(pChr, &packet);

}

bool RankDescendingOrder(CenterMatchPlayerInfo a, CenterMatchPlayerInfo b)
{
	return a > b;
}
//更新比赛排名
bool CenterMatchLogic::UpdateCenterMatchPlayerRank()
{
	//WGS_CENTERMATCHLOGIC_LOCK;

	if (m_RankList.empty())
	{
		CMPIter iter, ei = m_l_MatchPlayer.end();

		for (iter = m_l_MatchPlayer.begin(); iter != ei; iter++)
		{
			m_RankList.push_back(iter->second);
		}

		sort(m_RankList.begin(), m_RankList.end(), RankDescendingOrder);

		for (uint32 i = 0; i < m_RankList.size(); i++)
		{
			m_RankList[i].rank = i + 1;
			if (m_l_MatchPlayer.find(m_RankList[i].char_id) != m_l_MatchPlayer.end())
			{
				m_l_MatchPlayer[m_RankList[i].char_id].rank = i + 1;
				m_l_MatchPlayer[m_RankList[i].char_id].lastRank = i + 1;
			}
		}
	}
	else
	{
		std::vector<CenterMatchPlayerInfo > rankTemp;
		CMPIter iter, ei = m_l_MatchPlayer.end();
		for (iter = m_l_MatchPlayer.begin(); iter != ei; iter++)
		{
			rankTemp.push_back(iter->second);
		}

		sort(rankTemp.begin(), rankTemp.end(), RankDescendingOrder);
		for (uint32 i = 0; i < rankTemp.size(); i++)
		{
			if (m_l_MatchPlayer.find(rankTemp[i].char_id) != m_l_MatchPlayer.end())
			{
				if (m_l_MatchPlayer[rankTemp[i].char_id].lastRank < i + 1)
				{
					m_l_MatchPlayer[rankTemp[i].char_id].rankChangeStatus = enCenterMatchRankChangeStatus_UP;
				}
				else if (m_l_MatchPlayer[rankTemp[i].char_id].lastRank == i + 1)
				{
					m_l_MatchPlayer[rankTemp[i].char_id].rankChangeStatus = enCenterMatchRankChangeStatus_NoChange;
				}
				else if (m_l_MatchPlayer[rankTemp[i].char_id].lastRank > i + 1)
				{
					m_l_MatchPlayer[rankTemp[i].char_id].rankChangeStatus = enCenterMatchRankChangeStatus_Down;
				}
				m_l_MatchPlayer[rankTemp[i].char_id].lastRank = m_l_MatchPlayer[rankTemp[i].char_id].rank;
				m_l_MatchPlayer[rankTemp[i].char_id].rank = i + 1;
			}
		}
		m_RankList.clear();
		for (iter = m_l_MatchPlayer.begin(); iter != ei; iter++)
		{
			m_RankList.push_back(iter->second);
		}

		sort(m_RankList.begin(), m_RankList.end(), RankDescendingOrder);
	}

	CMPIter iter, ei = m_l_MatchPlayer.end();
	for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
	{
		uint32 char_id = iter->second.char_id;
		CharPtr pChr = sCharMgr.load(char_id);
		UserPtr pUser = sUserMgr.load(pChr->getUInt32Field("userid"));
		uint32 pid =0;
		if (pUser.isNull() == false)
		{
			pid = pUser->getUInt32Field("platform_id");
		}
		else
		{
			pid = sXmlDataMgr.getRobotShowPid(pChr->getHandle());
		}
		if (pid)
		{
			CenterMatchPlayer cmp;
			sCenterMatchPlayerMgr.GetCenterMatchPlayerInGameServer(m_cm_id, pid, &cmp);
			cmp.data4 = iter->second.score;
			cmp.data3 = iter->second.rankChangeStatus;
			cmp.data2 = iter->second.rank;
			cmp.sdata1 = StringConverter::toString(iter->second.status);
			cmp.sdata2 = iter->second.data1;
			sCenterMatchPlayerMgr.UpdateCenterMatchPlayer(cmp, cmp.update_key);
			Log.Debug("CenterMatchLogic::UpdateCenterMatchPlayerRank", "cm_id[%d] cm[%d] pid[%d] score[%d]", m_cm_id, cmp.cm_id, iter->second.pid, iter->second.score);
		}
	}

	CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);

	cm.data2 = m_RankList.size();
	sCenterMatchMgr.UpdateCenterMatch(cm, cm.update_key);
	return true;
}

//更新单一牌桌状态
bool CenterMatchLogic::UpdateChannelStatus(const uint32 & channel_id, const uint8 & status)
{
	if (m_l_MatchChannel.find(channel_id) == m_l_MatchChannel.end()) return false;
	CenterMatchChannelInfo & cmci = m_l_MatchChannel[channel_id];

	cmci.status = status;

	if (cmci.status == enCenterMatchChannelStatus_using)
	{
		for (uint8 i = 0; i < cmci.PlayerList.size(); i++)
		{
			CharPtr pChr = sCharMgr.load(cmci.PlayerList[i]);
			if (m_l_MatchPlayer.find(pChr->getHandle()) == m_l_MatchPlayer.end())
			{

			}
		}
	}
	return true;
}

//一个牌桌完成一轮游戏
bool CenterMatchLogic::ChannelFinishALoop(const uint32 & channel_id)
{
	//WGS_CENTERMATCHLOGIC_LOCK;
	WGS_CENTERMATCHLOGIC_LOCK;
	if (m_l_MatchChannel.find(channel_id) == m_l_MatchChannel.end()) return false;
	CenterMatchChannelInfo & channelInfo = m_l_MatchChannel[channel_id];
	channelInfo.m_matchStageContinueWaitTimer = time(0);
	Log.Success("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d]", channel_id);


	////	if (m_l_MatchChannel[channel_id].status != enCenterMatchChannelStatus_using) return false;

	//for (uint8 i = 0; i < channelInfo.PlayerList.size(); i++)
	//{//检测数据
	//	uint32 char_id = channelInfo.PlayerList[i];
	//	if (m_l_MatchPlayer.find(char_id) == m_l_MatchPlayer.end()) return false;
	//}

	//for (uint8 i = 0; i < channelInfo.PlayerList.size(); i++)
	//{
	//	uint32 char_id = channelInfo.PlayerList[i];
	//	Log.Debug("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d] char_id[%d]", channel_id, char_id);
	//	m_l_MatchPlayer[char_id].status = enCenterMatchPlayerStatus_Free;
	//	m_l_MatchPlayer[char_id].now_Channel = 0;
	//	m_l_MatchPlayer[char_id].last_Channel = channel_id;
	//}

	////	m_l_MatchChannel[channel_id].status != enCenterMatchChannelStatus_ended;

	//bool bAllEnd = true;

	//for (std::map<uint32, CenterMatchChannelInfo >::iterator iter = m_l_MatchChannel.begin(); iter != m_l_MatchChannel.end(); iter++)
	//{
	//	if (iter->second.status == enCenterMatchChannelStatus_using)
	//	{
	//		bAllEnd = false;
	//	}
	//}
	//if (bAllEnd)
	//{
	//	m_StageLoop++;
	//	Log.Success("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d] Add m_StageLoop[%d]", channel_id, m_StageLoop);
	//}

	////处理淘汰玩家

	///*if (m_MatchMode == enCenterMatchMode_TaoTaiSai && bAllEnd)
	//{
	//	if (m_StageLoop == m_CenterMatchStage.stage_loop)
	//	{
	//		EliminatePlayer();
	//	}
	//}*/
	////if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DingJuJiFen && bAllEnd)
	////{
	////	if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DingJuJiFen)
	////	{//定局积分
	////		for (std::map<uint32, CenterMatchPlayerInfo>::iterator iter = m_l_MatchPlayer.begin(); iter != m_l_MatchPlayer.end(); iter++)
	////		{
	////			if (iter->second.status != enCenterMatchPlayerStatus_Eliminate && iter->second.status != enCenterMatchPlayerStatus_WaitReturn)
	////			{
	////				if (m_CenterMatchStage.score_scaling != 0.0f)
	////				{
	////					iter->second.score *= m_CenterMatchStage.score_scaling;
	////				}
	////				CenterMatchChannelInfo * pCenterMatchChannel = &m_l_MatchChannel[iter->second.last_Channel];
	////				if (iter->second.score < pCenterMatchChannel->eliminate)
	////				{
	////					iter->second.status = enCenterMatchPlayerStatus_Eliminate;
	////				}
	////			}
	////		}
	////	}
	////	EliminatePlayer();
	////}
	////else if(m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu)
	////{
	////	EliminatePlayer();
	////}

	//uint32 stageStatus = StageCheck();
	//Log.Debug("CenterMatchLogic::ChannelFinishALoop", "cm_id[%d] stageStatus[%d] bAllEnd[%d]", m_cm_id, stageStatus, bAllEnd);
	//switch (stageStatus)
	//{
	//case enCenterMatchStage_Continue:
	//{
	//	/*	if (IsMatchPlayer())
	//		{
	//			AssignedToChannel();
	//		}
	//		*/
	//	m_MatchStageStatus = enCenterMatchStageStatus_Continue;
	//}
	//break;
	//case enCenterMatchStage_WaitGameingChannel:
	//{

	//	m_MatchStageStatus = enCenterMatchStageStatus_WaitOtherPlayer;
	//}
	//break;
	//case enCenterMatchStage_WaitNextStage:
	//{
	//	m_matchStageEndWaitTimer = time(0);
	//	/*if (GoToNextStage() == enCenterMatchNextStage_END)
	//	{
	//		MatchEnd();
	//		m_MatchStageStatus = enCenterMatchStageStatus_End;
	//		return true;
	//	}*/

	//}

	//break;
	//default:
	//	break;
	//}

	return true;
}

//检测牌桌本轮是否结束
uint8 CenterMatchLogic::ChannelBattleCheck(CenterMatchTotalLog & cmtt)
{
	//WGS_CENTERMATCHLOGIC_LOCK;
	Log.Debug("CenterMatchLogic::ChannelBattleCheck", "cm_id[%d] cmtt.channel_id[%d]", cmtt.cm_id, cmtt.channel_id);
	if (m_l_MatchChannel.find(cmtt.channel_id) == m_l_MatchChannel.end())
	{
		Log.Error("CenterMatchLogic::ChannelBattleCheck", "cm_id[%d] channel_id[%d] m_l_MatchChannel[%d] m_l_MatchPlayer[%d]", m_cm_id, cmtt.channel_id, m_l_MatchChannel.size(), m_l_MatchPlayer.size());
		String str = "";
		for (std::map<uint32, CenterMatchChannelInfo>::iterator iter = m_l_MatchChannel.begin(); iter != m_l_MatchChannel.end(); iter++)
		{
			str += StringConverter::toString(iter->second.ChannelId) + ",";
		}
		Log.Error("CenterMatchLogic::ChannelBattleCheck", "cm_id[%d] channel_id[%d] channel[%s]  addr[%x]", m_cm_id, cmtt.channel_id, str.c_str(), this);

		return false;
	}
	CenterMatchChannelInfo * pChannelInfo = &m_l_MatchChannel[cmtt.channel_id];

	for (uint8 i = 0; i < pChannelInfo->PlayerList.size(); i++)
	{
		uint32 playerCid = pChannelInfo->PlayerList[i];
		if (m_l_MatchPlayer.find(playerCid) == m_l_MatchPlayer.end())
		{
			Log.Debug("CenterMatchLogic::ChannelBattleCheck", "cm_id[%d] channel_id[%d] PlayerList[%d] m_l_MatchPlayer[%d]", m_cm_id, cmtt.channel_id, pChannelInfo->PlayerList.size(), m_l_MatchPlayer.size());

			return enCenterMatchChannelLoop_Error;
		}
	}

	uint8 result = enCenterMatchChannelLoop_Continue;


	if (m_MatchMode == enCenterMatchMode_JiFenSai)
	{
		uint32 _time = time(0);
		Log.Debug("CenterMatchLogic::ChannelBattleCheck", "cm_id[%d] _time[%d] m_matchStartWaitTimer[%d] m_CenterMatchStage.limit_time*60[%d] cmtt.loop[%d] m_CenterMatchStage.channel_limit_loop[%d]", m_cm_id, _time, m_matchStartWaitTimer, m_CenterMatchStage.limit_time, cmtt.loop, m_CenterMatchStage.channel_limit_loop);
		if (m_matchStartWaitTimer != 0 && m_CenterMatchStage.limit_time != 0 && _time - m_matchStartWaitTimer >= m_CenterMatchStage.limit_time * 60)
		{
			result = enCenterMatchChannelLoop_End;
		}
		else if (cmtt.loop == m_CenterMatchStage.channel_limit_loop)
		{
			result = enCenterMatchChannelLoop_End;
		}
	}
	else if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
	{
		if (cmtt.loop == m_CenterMatchStage.channel_limit_loop)
		{
			result = enCenterMatchChannelLoop_End;
		}
	}
	if (result == enCenterMatchChannelLoop_End)
	{
	//	pChannelInfo->status = enCenterMatchChannelStatus_ended;
	}
	Log.Debug("CenterMatchLogic::ChannelBattleCheck", "cmtt.channel_id[%d] result[%d]", cmtt.channel_id, result);

	//if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu)
	//{//打立出局立即检测分数
	//	result = DaLiChuJuCheck(cmtt.channel_id);
	//}
	//else if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DingJuJiFen)
	//{
	//	result = enCenterMatchChannelLoop_Continue;
	//}

	//if (cmtt.battleTimes == m_each_loop)
	//{
	//	if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu && result == enCenterMatchChannelLoop_End)
	//	{

	//	}
	//	result = enCenterMatchChannelLoop_End;
	//
	//}

	/*stCenterMatchModeInfo CenterMatchMode = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);

	if (CenterMatchMode.game_id == 0) return false;

	stCenterMatchStage nowStage = CenterMatchMode.matchStage[m_NowStage];

	nowStage.EndConditionList*/


	return result;
}

uint8 CenterMatchLogic::DaLiChuJuCheck(const uint32 & channel_id)
{
	CenterMatchChannelInfo * pChannelInfo = NULL;

	if (m_l_MatchChannel.find(channel_id) == m_l_MatchChannel.end())  return enCenterMatchChannelLoop_Error;

	pChannelInfo = &m_l_MatchChannel[channel_id];


	bool isJiXu = enCenterMatchChannelLoop_Continue;
	for (uint8 i = 0; i < pChannelInfo->PlayerList.size(); i++)
	{
		uint32 char_id = pChannelInfo->PlayerList[i];
		if (m_l_MatchPlayer.find(char_id) == m_l_MatchPlayer.end())
			continue;
		if (pChannelInfo->eliminate > m_l_MatchPlayer[char_id].score)
		{
			m_l_MatchPlayer[char_id].status = enCenterMatchPlayerStatus_Eliminate;
			isJiXu = enCenterMatchChannelLoop_End;
		}
	}



	return isJiXu;
}

//定局积分规则下的检测
uint8 CenterMatchLogic::DingJuJiFenCheck(const uint32 & channel_id)
{

	CenterMatchChannelInfo * pChannelInfo = NULL;

	if (m_l_MatchChannel.find(channel_id) == m_l_MatchChannel.end())  return false;

	pChannelInfo = &m_l_MatchChannel[channel_id];


	bool isJiXu = false;
	for (uint8 i = 0; i < pChannelInfo->PlayerList.size(); i++)
	{
		uint32 char_id = pChannelInfo->PlayerList[i];
		if (m_l_MatchPlayer.find(char_id) == m_l_MatchPlayer.end())
			continue;
		m_l_MatchPlayer[char_id].score *= m_CenterMatchStage.score_scaling;
		if (pChannelInfo->eliminate > m_l_MatchPlayer[char_id].score)
		{
			m_l_MatchPlayer[char_id].status = enCenterMatchPlayerStatus_Eliminate;
			isJiXu = true;
		}
	}



	return isJiXu;
}

//阶段进度检测
uint8 CenterMatchLogic::StageCheck()
{
	stCenterMatchModeInfo CenterMatchMode = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);

	uint8 result = enCenterMatchStage_Continue;
	bool bAllEnd = true;
	std::map<uint32, CenterMatchChannelInfo>::iterator iter, ei = m_l_MatchChannel.end();
	for (iter = m_l_MatchChannel.begin(); iter != ei; ++iter)
	{
		if (iter->second.status == enCenterMatchChannelStatus_using)
		{
			bAllEnd = false;
		}
		/*{
			result = enCenterMatchStage_WaitNextStage;
			Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] channel[%d]iter->second.battle_times[%d] m_CenterMatchStage.stage_loop[%d]", m_cm_id, iter->first, iter->second.battle_times, m_CenterMatchStage.channel_limit_loop);
		}*/
	}
	if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
	{
		if (m_StageLoop == m_CenterMatchStage.stage_loop && bAllEnd == true)
		{
			result = enCenterMatchStage_WaitNextStage;
			Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] m_StageLoop[%d] m_CenterMatchStage.stage_loop[%d] bAllEnd[%d]", m_cm_id, m_StageLoop, m_CenterMatchStage.stage_loop, bAllEnd);
		}
		else
		{
			if (bAllEnd == false && m_StageLoop == m_CenterMatchStage.stage_loop)
			{
				ASSERT(0);
			}
			if (bAllEnd == false)
			{
				result = enCenterMatchStage_WaitGameingChannel;
				Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] result[%d]", m_cm_id, result);
			}
		}
		//if (CenterMatchMode.matchStage[m_NowStage].stageMode == enCenterMatchRuleMode_DaLiChuJu)
		//{//打立出局 剩余玩家数到达就结束
		//	uint32 nowPlayer = m_l_MatchPlayer.size() - GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Eliminate) - GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_WaitReturn);
		//	if (m_CenterMatchStage.EndConditionList[m_NowStage].endType == enEndConditionType_battleNum)
		//	{
		//		if (m_NowLoop >= m_CenterMatchStage.EndConditionList[m_NowStage].endNumber)
		//		{
		//			if (GetMatchChannelNumInfo(enCenterMatchChannelStatus_using) != 0)
		//				result = enCenterMatchStage_WaitGameingChannel;
		//			else
		//				result = enCenterMatchStage_WaitNextStage;
		//		}
		//	}
		//	else if (m_CenterMatchStage.EndConditionList[m_NowStage].endType == enEndConditionType_playerNum)
		//	{
		//		if (nowPlayer <= m_CenterMatchStage.EndConditionList[m_NowStage].endNumber)
		//		{
		//			if (GetMatchChannelNumInfo(enCenterMatchChannelStatus_using) != 0)
		//				result = enCenterMatchStage_WaitGameingChannel;
		//			else
		//				result = enCenterMatchStage_WaitNextStage;
		//		}
		//	}
		//}
		//else if (CenterMatchMode.matchStage[m_NowStage].stageMode == enCenterMatchRuleMode_DingJuJiFen)
		//{//定局积分
		//	if (m_StageLoop >= CenterMatchMode.matchStage[m_NowStage].stage_loop)
		//		result = enCenterMatchStage_WaitNextStage;
		//}
	}
	else if (m_MatchMode == enCenterMatchMode_JiFenSai)
	{
		/*	if (m_MatchLimit_Time == 0)
			{
				Log.Error("CenterMatchLogic::StageCheck", "cm_id:%d  mode:%d   Match LimitTime == 0", m_cm_id, m_MatchMode);
				return result;
			}*/


	/*	std::map<uint32, CenterMatchChannelInfo>::iterator iter, ei = m_l_MatchChannel.end();
		for (iter = m_l_MatchChannel.begin(); iter != ei; ++iter)
		{
			if (iter->second.battle_times >= m_CenterMatchStage.channel_limit_loop)
			{
				result = enCenterMatchStage_WaitGameingChannel;
				Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] channel[%d] inJiFen iter->second.battle_times[%d] m_CenterMatchStage.stage_loop[%d]", m_cm_id, iter->first, iter->second.battle_times, m_CenterMatchStage.channel_limit_loop);

				break;
			}
		}*/

		uint32 _time = time(0);
		Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] m_matchStartWaitTimer[%d] _time[%d] m_CenterMatchStage.limit_time[%d]", m_cm_id, m_matchStartWaitTimer, _time, m_CenterMatchStage.limit_time);
		if (m_matchStartWaitTimer != 0 && m_CenterMatchStage.limit_time != 0 && _time - m_matchStartWaitTimer >= m_CenterMatchStage.limit_time * 60)
		{
			if (bAllEnd)
			{
				result = enCenterMatchStage_WaitNextStage;
				Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] bAllEnd[%d] result[%d]", m_cm_id, bAllEnd, result);
			}
			else
			{
				result = enCenterMatchStage_WaitGameingChannel;
				Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] bAllEnd[%d] result[%d]", m_cm_id, bAllEnd, result);

			}

		}
		else
		{
			result = enCenterMatchStage_Continue;

		}
		/*else if (bAllEnd)
		{
			result = enCenterMatchStage_WaitNextStage;
			Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] In time bAllEnd[%d] result[%d]", m_cm_id, bAllEnd, result);
		}*/
	}
	Log.Debug("CenterMatchLogic::StageCheck", "cm_id[%d] result[%d]", m_cm_id, result);

	return result;
}

//进入下一个阶段
uint8 CenterMatchLogic::GoToNextStage()
{
	stCenterMatchModeInfo  CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);
	if (m_CenterMatchStage.stageMode == 0)
	{
		m_CenterMatchStage = CenterMatchModeInfo.matchStage.front();
		Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] First Stage MatchMode[%d] CenterMatchModeInfo.matchMode[%d] stageMode[%d]", m_cm_id, m_MatchMode, CenterMatchModeInfo.matchMode, m_CenterMatchStage.stageMode);
	}
	if (CenterMatchModeInfo.matchMode == enCenterMatchMode_TaoTaiSai)
	{
		if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_Default)
		{
			return enCenterMatchNextStage_OK;
		}

		//-----------循环阶段维护----------------
		if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DingJuJiFen)
		{//定局积分
			if (/*m_CenterMatchStage.stageRule.empty()*/stageRule.empty() == false)
			{
				Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] stageRule[%s]", m_cm_id, stageRule.c_str());
			
				//if (iter->second.status != enCenterMatchPlayerStatus_Eliminate && iter->second.status != enCenterMatchPlayerStatus_WaitReturn)
				uint32 nowPlayer = m_l_MatchPlayer.size() - (GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Eliminate) + GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_WaitReturn));
				if (m_CenterMatchStage.eliminateMode == enCenterMatchEliminateMode_TableRankFirst)
				{
					if (stageRule.empty())
					{
						stageRule += StringConverter::toString(nowPlayer);
						uint32 playerNumTemp = nowPlayer;
						do
						{
							stageRule += "-";
							stageRule += StringConverter::toString(CenterMatchModeInfo.eachChannelPlayer * (playerNumTemp / CenterMatchModeInfo.eachChannelPlayer / 2));
							playerNumTemp = CenterMatchModeInfo.eachChannelPlayer * (playerNumTemp / CenterMatchModeInfo.eachChannelPlayer / 2);
							if (playerNumTemp == 0)
								playerNumTemp = 1;
						} while (playerNumTemp != 1);
						stageRule += "-1";
					}
				}
				std::vector<String> vals = StringUtil::split(stageRule, "-");

				uint32 num = m_NextRoundNum, max = 0;
				if (vals.size())
				{
					max = StringConverter::parseInt(vals[vals.size() - 1]);
				}
				Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] max[%d]", m_cm_id, max);
				if (nowPlayer <= max)
				{
					//if (m_bFinals)
					return enCenterMatchNextStage_END;
					//m_bFinals = true;
				}
				for (uint8 i = 0; i < vals.size(); i++)
				{
					if (i >= vals.size() - 1)
					{
						if (num == m_NextRoundNum)
							return enCenterMatchNextStage_END;
						else
							break;	
					}
					uint32 max = StringConverter::parseInt(vals[i]);
					uint32 min = StringConverter::parseInt(vals[i + 1]);
					Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] max[%d] nowPlayer[%d] min[%d]", m_cm_id, max, nowPlayer, min);

					if (max >= nowPlayer && nowPlayer > min)
					{
						m_NowStage = i + 1;
						num = min;
						if (i == vals.size() - 2)
							m_bFinals = true;
						Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] m_NowStage[%d] num[%d]", m_cm_id, m_NowStage, num);
					}
				}

				if (num == 0)
				{
					Log.Error("CenterMatchLogic::GoToNextStage", "Game_ID:%u GameMode:%u num == 0", m_game_id, m_MatchMode);
					return 0;
				}
				m_StageLoop = 0;
				m_NextRoundNum = num;
				Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] m_NextRoundNum[%d]", m_cm_id, m_NextRoundNum);

				//	return enCenterMatchNextStage_OK;
			}
		}

		/*if (m_NowStage + 1 > CenterMatchModeInfo.matchStage.size())
		{
			Log.Error("CenterMatchLogic::GoToNextStage", "cm_id:%u m_MatchMode:%u m_NowStage:%d", m_cm_id, m_MatchMode, m_NowStage);
			return 0;
		}
		else if (m_NowStage + 1 == CenterMatchModeInfo.matchStage.size())
		{
			return enCenterMatchNextStage_END;
		}

		m_CenterMatchStage = CenterMatchModeInfo.matchStage[m_NowStage + 1];*/

		if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DingJuJiFen)
		{//定局积分
			Log.Debug("CenterMatchLogic::GoToNextStage", "cm_id[%d] m_l_MatchPlayer[%d] m_CenterMatchStage.init_score_scaling[%f]", m_cm_id, m_l_MatchPlayer.size(), m_CenterMatchStage.init_score_scaling);
			for (std::map<uint32, CenterMatchPlayerInfo>::iterator iter = m_l_MatchPlayer.begin(); iter != m_l_MatchPlayer.end(); iter++)
			{
				if (iter->second.status != enCenterMatchPlayerStatus_Eliminate && iter->second.status != enCenterMatchPlayerStatus_WaitReturn)
				{
					//if (m_CenterMatchStage.init_score_scaling != 0.0f)
					{
						iter->second.score *= m_CenterMatchStage.init_score_scaling;
					}
				}
			}
		}
		else if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu)
		{//大力出局

		}
	}
	else if (CenterMatchModeInfo.matchMode == enCenterMatchMode_JiFenSai)
	{
		uint32 _time = time(0);
		if (m_matchStartWaitTimer != 0 && m_CenterMatchStage.limit_time != 0 && _time - m_matchStartWaitTimer >= m_CenterMatchStage.limit_time * 60)
		{
			m_bFinals = true;
			return enCenterMatchNextStage_END;
		}
	}
	return enCenterMatchNextStage_OK;
}

//是否可以进行玩家匹配
bool CenterMatchLogic::IsMatchPlayer()
{
	return true;
	//WGS_CENTERMATCHLOGIC_LOCK;
	uint8 result = false;
	stCenterMatchModeInfo  CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);
	if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
	{
		if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu)
		{
			if (GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) >= CenterMatchModeInfo.limit_match_num)
			{
				result = true;
			}
		}
	}
	else if (m_MatchMode == enCenterMatchMode_JiFenSai)
	{
		uint32 _time = time(0);
		if (_time - m_MatchBeginTime < m_MatchLimit_Time)
		{
			result = true;
		}
	}

	return result;
}

//统计被淘汰的玩家
void CenterMatchLogic::EliminatePlayer()
{
	uint32 nowPlayerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free);
	EliminatePlayerByMode(1);
	//if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
	//{
	//	if (m_NextRoundNum && GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) < m_NextRoundNum)
	//	{
	//		Log.Error("CenterMatchLogic::EliminatePlayer", "m_NextRoundNum[%d] FreePlayer[%d]", m_NextRoundNum, GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free));
	//		return;
	//	}
	//	if (m_NextRoundNum < m_RankList.size())
	//	{
	//		for (uint32 i = m_NextRoundNum; i < m_RankList.size(); i++)
	//		{
	//			CMPIter iter = m_l_MatchPlayer.find(m_RankList[i].char_id);
	//			if (iter != m_l_MatchPlayer.end())
	//			{
	//				iter->second.status = enCenterMatchPlayerStatus_Eliminate;
	//				/*	m_TaoTaiPlayerList[iter->second.char_id] = iter->second;
	//					m_l_MatchPlayer.erase(iter);*/
	//			}
	//		}
	//	}
	//	else
	//	{
	//		Log.Error("CenterMatchLogic::EliminatePlayer", "m_NextRoundNum[%d] FreePlayer[%d]", m_NextRoundNum, GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free));
	//		return;
	//	}
	//}

	CMPIter iter, ei = m_l_MatchPlayer.end();
	std::vector<uint32> outList;
	for (iter = m_l_MatchPlayer.begin(); iter != ei;)
	{
		WorldPacket packet;
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		if (iter->second.status == enCenterMatchPlayerStatus_Eliminate)
		{
			if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iter->second.rank, nowPlayerNum,0, std::map<uint32, uint32>(),"", enCenterMatchGameResult_Out))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
			m_TaoTaiPlayerList[iter->first] = iter->second;
			outList.push_back(iter->first);
			m_l_MatchPlayer.erase(iter++);
			uint32 pid = 0;
			UserPtr pUser = sUserMgr.load(pChr->getUInt32Field("userid"));
			if (pUser.isNull() == false)
			{
				pid = pUser->getUInt32Field("platform_id");
			}
			if (iter->second.bCenterRobot)
			{
				pid = sXmlDataMgr.getRobotShowPid(iter->second.char_id);
			}
			pChr->setStatus(CharacterStatusFree);
			pChr->SaveDB();
			CenterMatchPlayer cmp;
			sCenterMatchPlayerMgr.GetCenterMatchPlayerInGameServer(m_cm_id, pid, &cmp);
			cmp.sdata1 = StringConverter::toString(enCenterMatchPlayerStatus_Eliminate);
			sCenterMatchPlayerMgr.UpdateCenterMatchPlayer(cmp, cmp.update_key);
			continue;
		}
		else
		{
			if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iter->second.rank, nowPlayerNum,0, std::map<uint32, uint32>(),"", enCenterMatchGameResult_Rise))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
		}
		++iter;
	}
	/*CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
	for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
	{
		WorldPacket packet;
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, m_l_MatchPlayer))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}*/

	/*for (uint32 i = 0; i < outList.size(); i++)
	{
		CharPtr pChr = sCharMgr.load(outList[i]);

		WorldPacket packet;
		if (sProtocolsMgr.CreateDissolveChannelPacket(&packet, DissolveType_CenterMathLose))
			sGLMgr.SendProtocolsToChr(pChr, &packet);

	}*/
}

void CenterMatchLogic::EliminatePlayerByMode(const uint8 & type)
{
	if (m_CenterMatchStage.eliminateMode == 0)
	{
		return;
	}
	else if (m_CenterMatchStage.eliminateMode == enCenterMatchEliminateMode_MatchRankFirst)
	{
		uint32 nowPlayerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free);
		if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
		{
			if (m_NextRoundNum && GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) < m_NextRoundNum)
			{
				Log.Error("CenterMatchLogic::EliminatePlayer", "m_NextRoundNum[%d] FreePlayer[%d]", m_NextRoundNum, GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free));
				return;
			}
			if (m_NextRoundNum < m_RankList.size())
			{
				for (uint32 i = m_NextRoundNum; i < m_RankList.size(); i++)
				{
					CMPIter iter = m_l_MatchPlayer.find(m_RankList[i].char_id);
					if (iter != m_l_MatchPlayer.end())
					{
						iter->second.status = enCenterMatchPlayerStatus_Eliminate;
						/*	m_TaoTaiPlayerList[iter->second.char_id] = iter->second;
						m_l_MatchPlayer.erase(iter);*/
					}
				}
			}
			else
			{
				Log.Error("CenterMatchLogic::EliminatePlayer", "m_NextRoundNum[%d] FreePlayer[%d]", m_NextRoundNum, GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free));
				return;
			}
		}
	}
	else if (m_CenterMatchStage.eliminateMode == enCenterMatchEliminateMode_TableRankFirst)
	{
		uint32 nowChannels = GetMatchChannelNumInfo(enCenterMatchChannelStatus_ended);
		uint32 RiseUpNum = 3 * (nowChannels / 2);
		std::map<uint32, CenterMatchChannelInfo>::iterator iter, ei = m_l_MatchChannel.end();
		std::vector<CenterMatchPlayerInfo > playerList;

		for (iter = m_l_MatchChannel.begin(); iter != ei; ++iter)
		{
		    std::vector<CenterMatchPlayerInfo > socreRank;
			for (uint8 i = 0; i < iter->second.PlayerList.size(); ++i)
			{
				CMPIter cmiter = m_l_MatchPlayer.find(iter->second.PlayerList[i]);
				if (cmiter != m_l_MatchPlayer.end())
				{
					socreRank.push_back(cmiter->second);
				}
			}
			sort(socreRank.begin(), socreRank.end(), RankDescendingOrder);
			for (uint8 i = 0; i < socreRank.size(); i++)
			{
				if (i == 0)
				{
					CMPIter cmiter = m_l_MatchPlayer.find(socreRank[i].char_id);
				//	cmiter->second.status = enCenterMatchPlayerStatus_Rise;
				}
				else if(i == socreRank.size() - 1)
				{
					CMPIter cmiter = m_l_MatchPlayer.find(socreRank[i].char_id);
					cmiter->second.status = enCenterMatchPlayerStatus_Eliminate;
				}
				else
				{
					playerList.push_back(socreRank[i]);
				}
			}
		}

		sort(playerList.begin(), playerList.end(), RankDescendingOrder);

		if (RiseUpNum > nowChannels)
		{
			RiseUpNum -= nowChannels;
		}
		for (int i = RiseUpNum; i < playerList.size(); i++)
		{
			CMPIter cmiter = m_l_MatchPlayer.find(playerList[i].char_id);
			cmiter->second.status = enCenterMatchPlayerStatus_Eliminate;
		}
	}
}

//比赛结束
void CenterMatchLogic::MatchEnd()
{
	//WGS_CENTERMATCHLOGIC_LOCK;
	CMPIter iter = m_l_MatchPlayer.begin(), ei = m_l_MatchPlayer.end();

	for (; iter != ei; ++iter)
	{
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		if (pChr.isNull() == false)
		{
			pChr->setStatus(CharacterStatusFree);
			pChr->SaveDB();
			if (m_MatchStatus == enCenterMatchStatus_Pre)
			{
				WorldPacket packet;
				if (sProtocolsMgr.CreateDissolveChannelPacket(&packet, DissolveType_CenterMathOver))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
			}
		}
	
		Log.Debug("CenterMatchLogic::MatchEnd", "Char[%d] Set free and CreateDissolveChannelPacket[\"DissolveType_CenterMathOver\"]", pChr->getHandle());
	}
	m_MatchStatus = enCenterMatchStatus_End;


}

//获取需要的牌桌数量
uint32 CenterMatchLogic::GetMatchNeedChannelNum(const uint8 & dataType)
{
	uint32 playerNum = 0;
	Log.Debug("CenterMatchLogic::GetMatchNeedChannelNum", "cm_id[%d] type[%d]", m_cm_id, dataType);
	switch (dataType)
	{
	case enCenterMatchPlayerStatus_Free:
	{
		playerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free);

	}
	break;
	case enCenterMatchPlayerStatus_WaitReMatching:
	{
		playerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_WaitReMatching);
	}
	break;
	default:
		break;
	}

	stCenterMatchModeInfo CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);

	uint32 eachChannelPlayerNum = CenterMatchModeInfo.eachChannelPlayer;



	Log.Debug("CenterMatchLogic::GetMatchNeedChannelNum", "cm_id[%d] playerNum[%d] m_MatchMode[%d] agent_id[%d] eachChannelPlayerNum[%d]", m_cm_id, playerNum, m_MatchMode, CenterMatchModeInfo.agent_id, CenterMatchModeInfo.eachChannelPlayer);
	return playerNum / eachChannelPlayerNum;
}

//比赛人数数据
uint32 CenterMatchLogic::GetMatchPlayerNumInfo(const uint8 & dataType)
{
	uint32 num = 0;
	std::map<uint32, CenterMatchPlayerInfo >::iterator iter, ei = m_l_MatchPlayer.end();

	for (iter = m_l_MatchPlayer.begin(); iter != ei; iter++)
	{
		if (iter->second.status == dataType)
		{
			num++;
		}
	}
	
	return num;
}

//比赛牌桌数数据
uint32 CenterMatchLogic::GetMatchChannelNumInfo(const uint8 & dataType)
{
	uint32 num = 0;
	std::map<uint32, CenterMatchChannelInfo >::iterator iter, ei = m_l_MatchChannel.end();

	for (iter = m_l_MatchChannel.begin(); iter != ei; iter++)
	{
		if (iter->second.status == dataType)
			num++;
	}

	return num;
}

bool CenterMatchLogic::IsMatchWantDelet()
{
	return false;
}

//瑞士分桌
bool CenterMatchLogic::SwitzerlandShiftOrder()
{
	UpdateCenterMatchPlayerRank();
	stCenterMatchModeInfo  CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);
	std::map<uint32, CenterMatchChannelInfo >::iterator iter, ei = m_l_MatchChannel.end();

	std::vector<CenterMatchPlayerInfo >  ScoreList = m_RankList;


	uint8 eachChannelPlayerNum = CenterMatchModeInfo.eachChannelPlayer;

	std::vector<uint8 > IndexAdd;
	for (uint8 i = 1; i < eachChannelPlayerNum - 1; i++)
	{
		IndexAdd.push_back(i);
	}

	//for (uint32 i = 0; i < ScoreList.size(); i++)
	//{
	//	uint32 ChannelId = ScoreList[i].last_Channel;
	//	if (m_l_MatchChannel.find(ChannelId) == m_l_MatchChannel.end())
	//	{
	//		m_l_MatchPlayer.find(ScoreList[i].char_id)->second.status = enCenterMatchPlayerStatus_Eliminate;
	//	}
	//	CenterMatchChannelInfo * pCMCI = &m_l_MatchChannel[ChannelId];
	//	if (pCMCI->bAss == false) continue;
	//	uint32 SameCount = 1;
	//	uint8 status = 0;
	//	for (uint8 t = 0; t < IndexAdd.size(); t++)
	//	{
	//		uint8 index = i + IndexAdd[i];
	//		if (index >= ScoreList.size())
	//		{
	//			status = 3;
	//			break;
	//		}
	//		uint32 ChannelIdTemp = ScoreList[index].last_Channel;
	//		if (m_l_MatchChannel.find(ChannelIdTemp) == m_l_MatchChannel.end())
	//		{
	//			m_l_MatchPlayer.find(ScoreList[index].char_id)->second.status = enCenterMatchPlayerStatus_Eliminate;
	//			continue;
	//		}
	//		if (ChannelId == ChannelId)
	//		{
	//			SameCount++;
	//		}
	//		else
	//		{
	//			i += IndexAdd.back();
	//			status = 1;
	//			break;	
	//		}
	//		if (SameCount >= eachChannelPlayerNum)
	//		{
	//			if (index + 1 < ScoreList.size())
	//			{
	//				std::swap(ScoreList[index], ScoreList[index + 1]);
	//				i += index;
	//				status = 1;
	//			}
	//			else
	//			{
	//				for (uint8 j = 0; j < IndexAdd.size(); j++)
	//				{
	//					ScoreList[i + IndexAdd[j]].status = enCenterMatchPlayerStatus_WaitReMatching;
	//					m_l_MatchPlayer.find(ScoreList[i + IndexAdd[j]].char_id)->second.status = enCenterMatchPlayerStatus_WaitReMatching;
	//				}
	//				status = 3;
	//			}
	//			break;
	//		}
	//	}
	//	if (status == 3)
	//	{
	//		break;
	//	}
	//	else if (status == 1 || status == 2) continue;
	//}

	CreateChannels(enCenterMatchPlayerStatus_Free);

	//uint32 pos = 0;

	std::vector<CenterMatchPlayerInfo >::iterator /*iter2 = ScoreList.begin(),*/ ei2 = ScoreList.end();

	for (uint32 i = 0; i < ScoreList.size(); i++)
	{
		Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] status[%d]", m_cm_id, ScoreList[i].char_id, ScoreList[i].status);

	}
	CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
	Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] ScoreList[%d]", m_cm_id, ScoreList.size());
	for (iter = m_l_MatchChannel.begin(); iter != ei; iter++)
	{
		ChannelPtr pChannel = sChannelMgr.load(iter->second.ChannelId);  

		Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] Channel[%d] status[%d]", m_cm_id, iter->second.ChannelId, iter->second.status);
		std::map<uint32, uint32>  ChannelIdLog;

		if (pChannel.isNull()) continue;

		if (iter->second.status != enCenterMatchChannelStatus_ready)  continue;

		AIChannelBaseInterface * pChannelInterface = TO_CHANNEL_BASE_INTERFACE(pChannel->getAIInterface());

		Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] pChannelInterface[%x]", m_cm_id, pChannelInterface);
		if (pChannelInterface == NULL) continue;

		Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] Channel[%d]", m_cm_id, pChannel->getHandle());
		std::vector<CenterMatchPlayerInfo >::iterator iter3 = ScoreList.begin();
		if (iter3 == ei2)
		{
			Log.Error("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] Channel[%d] No Player join ?", m_cm_id, pChannel->getHandle());
			ASSERT(0);
		}
		CenterMatchTotalLog  CMPDU;

		while (iter3 != ei2)
		{
			if (ei2 == iter3)
			{
				Log.Error("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] Channel[%d] No Player join in eachChannelPlayerNum ?", m_cm_id, pChannel->getHandle());
				ASSERT(0);
			}
		


			CharPtr pChr = sCharMgr.load(iter3->char_id);
			CenterMatchPlayerInfo * pCenterMatchPlayer = &(m_l_MatchPlayer.find(iter3->char_id)->second);

			Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] iter3->status[%d]", m_cm_id, pCenterMatchPlayer->char_id, iter3->status);
			if (pChr.isNull() || pCenterMatchPlayer->status != enCenterMatchPlayerStatus_Free)
			{
				iter3++;
				Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] status continue", m_cm_id, pCenterMatchPlayer->char_id);
				if (iter3 == ei2) break;
				continue;
			}
			if (pCenterMatchPlayer->now_Channel != 0)
			{
				iter3++;
				Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] now_Channel continue", m_cm_id, pCenterMatchPlayer->char_id);
				if (iter3 == ei2) break;
				continue;
			}
			if (pCenterMatchPlayer->last_Channel != 0 && ChannelIdLog[pCenterMatchPlayer->last_Channel]++ >= 2 && ScoreList.size() >= eachChannelPlayerNum)
			{
				iter3++;
				Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] ChannelIdLog continue", m_cm_id, pCenterMatchPlayer->char_id);
				if (iter3 == ei2) break;
				continue;
			}

			Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] try join[%d]", m_cm_id, pCenterMatchPlayer->char_id, pChannel->getHandle());
			//	if (pChannelInterface->JoinChannel(pChr, false))
			CenterMatchPlayerDataUpdate cmpdu;
			{
				cmpdu.char_id = iter3->char_id;
				CMPDU.list.push_back(cmpdu);
				iter->second.PlayerList.push_back(iter3->char_id);
			}
			if (CMPDU.list.size() == eachChannelPlayerNum && iter->second.PlayerList.size() == eachChannelPlayerNum)
			{
				Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] get[%d] player, joining", eachChannelPlayerNum);
				break;
			}
			iter3++;
		}
		if (CMPDU.list.size() == eachChannelPlayerNum && iter->second.PlayerList.size() == eachChannelPlayerNum)
		{
			for (uint32 i = 0; i < iter->second.PlayerList.size(); i++)
			{
				CharPtr pChr = sCharMgr.load(iter->second.PlayerList[i]);
				CenterMatchPlayerInfo * pCenterMatchPlayer = &(m_l_MatchPlayer.find(iter->second.PlayerList[i])->second);
				
				iter->second.status = enCenterMatchChannelStatus_using;
				pCenterMatchPlayer->status = enCenterMatchPlayerStatus_InChannel;
				pCenterMatchPlayer->now_Channel = iter->second.ChannelId;
				pCenterMatchPlayer->status = enCenterMatchPlayerStatus_InChannel;
				pCenterMatchPlayer->now_Channel = iter->second.ChannelId;
			
				pChannelInterface->JoinChannel(pChr, true);
				WorldPacket packet;
				if (sProtocolsMgr.CreateCenterMatchJoinChannelPacket(&packet, pChannel->getHandle(), enCenterMatchResult_Sucess))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				SendCenterMatchChannelMatchInfo(CMPDU);
				Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] char_id[%d] join[%d] ok", m_cm_id, pCenterMatchPlayer->char_id, pChannel->getHandle());
				CMPDU.list.clear();
			}
		}
		else
		{
			iter->second.PlayerList.clear();
		}
	//	iter2 = iter3;
	}
	uint32 nowPlayerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) + GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_InChannel);
	uint32 nowChannels = GetMatchChannelNumInfo(enCenterMatchChannelStatus_using);
	for (std::map<uint32, CenterMatchPlayerInfo >::iterator iter2 = m_l_MatchPlayer.begin(); iter2 != m_l_MatchPlayer.end(); iter2++)
	{
		if (iter2->second.status != enCenterMatchPlayerStatus_InChannel)
		{
			CharPtr pChr = sCharMgr.load(iter2->second.char_id);
			WorldPacket packet;
			if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iter2->second.rank, nowPlayerNum, nowChannels, std::map<uint32, uint32>(), "", enCenterMatchGameResult_LunKong))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
		}
		
		/*if (iter2->second.status == enCenterMatchPlayerStatus_WaitReMatching)
		{
			iter2->second.status = enCenterMatchPlayerStatus_Free;
		}*/
	}
	Log.Debug("CenterMatchLogic::SwitzerlandShiftOrder", "cm_id[%d] channels[%d] FreePlayer[%d]  Fight[%d]", m_cm_id, m_l_MatchChannel.size(),GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free), GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_InChannel));

	return true;
}

//分数相近分桌
bool CenterMatchLogic::ScoreNearlyOrder()
{
	stCenterMatchModeInfo  CenterMatchModeInfo = sXmlDataMgr.GetCenterMatchModeInfo(m_agent_id, m_MatchMode);
	std::map<uint32, CenterMatchChannelInfo >::iterator iter, ei = m_l_MatchChannel.end();

	//uint8 eachChannelPlayerNum = CenterMatchModeInfo.eachChannelPlayer;
	for (uint32 i = 0; i < m_RankList.size(); i++)
	{
		uint32 ChannelId = m_RankList[i].last_Channel;
		if (m_l_MatchChannel.find(ChannelId) == m_l_MatchChannel.end() && ChannelId != 0)
		{
			m_l_MatchPlayer.find(m_RankList[i].char_id)->second.status = enCenterMatchPlayerStatus_Eliminate;
		}
		CenterMatchChannelInfo * pCMCI = &m_l_MatchChannel[ChannelId];
		if (pCMCI->bAss == false) continue;
	}
	CreateChannels(enCenterMatchPlayerStatus_Free);

	for (uint32 i = 0; i < m_RankList.size(); i++)
	{

	}
	return true;
}

//重分配玩家开始分配
uint8 CenterMatchLogic::ReMatchingPlayer()
{
	uint8 rematchingNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_WaitReMatching);

	if (rematchingNum == 0)
	{
		return 0;
	}

	std::map<uint32, CenterMatchChannelInfo >::iterator iter, ei = m_l_MatchChannel.end();

	for (iter = m_l_MatchChannel.begin(); iter != ei; iter++)
	{

	}
	return 0;
}

//玩家加入比赛
uint8 CenterMatchLogic::PlayerJoinMatch(UserPtr & pUser)
{
	uint8 result = 0;
	if (pUser.isNull())
	{
		return result;
	}
	CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
	CenterMatchPlayerInfo cmpi;
	CenterMatch cm;
	do
	{
		if (m_l_MatchPlayer.find(pChr->getHandle()) != m_l_MatchPlayer.end())
		{
			cmpi = m_l_MatchPlayer.find(pChr->getHandle())->second;
			result = enCenterMatchJoinGameMatch_InMatch;
			break;
		}
		result = enCenterMatchResult_Sucess;
	} while (0);
	if (result == enCenterMatchResult_Sucess)
	{
		cmpi.char_id = pUser->getUInt32Field("char_id");
		cmpi.pid = pUser->getUInt32Field("platform_id");
		Json::Value val;
		val["pid"] = cmpi.pid;
		val["desc"] = pChr->getStringField("desc");
		val["name"] = pChr->getStringField("name");
		cmpi.status = enCenterMatchPlayerStatus_Free;
		m_l_MatchPlayer.insert(std::make_pair(cmpi.char_id, cmpi));
		CenterMatchPlayer cmp;
		sCenterMatchPlayerMgr.GetCenterMatchPlayerInGameServer(m_cm_id, pUser->getUInt32Field("platform_id"), &cmp);
		cmp.enter_status = enCenterMatchEnterStatus_Passed;
		sCenterMatchPlayerMgr.UpdateCenterMatchPlayer(cmp, cmp.update_key);
		sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
		cm.now_player++;
	//	cm.now_enter_num++;
		sCenterMatchMgr.UpdateCenterMatch(cm, cm.update_key);
	

		WorldPacket packet;
		CMPIter iter, ei = m_l_MatchPlayer.end();
		for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
		{
			CharPtr pChrInMatch = sCharMgr.getByHandle(iter->second.char_id);
			if (pChrInMatch.isNull() == false)
			{
				if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
					sGLMgr.SendProtocolsToChr(pChrInMatch, &packet);
			}
		}
	
	}
	else if (result == enCenterMatchJoinGameMatch_InMatch)
	{
		result = enCenterMatchResult_Sucess;
		if (cmpi.char_id != 0 && cmpi.now_Channel != 0)
		{
			if (m_l_MatchChannel.find(cmpi.now_Channel) != m_l_MatchChannel.end())
			{
				CenterMatchChannelInfo cmci = m_l_MatchChannel.find(cmpi.now_Channel)->second;
				std::map<uint32, CenterMatchPlayerInfo> temp;
				for (uint32 i = 0; i < cmci.PlayerList.size(); i++)
				{
					if (m_l_MatchPlayer.find(cmci.PlayerList[i]) != m_l_MatchPlayer.end())
					{
						CenterMatchPlayerInfo cmpTemp = m_l_MatchPlayer.find(cmci.PlayerList[i])->second;
						temp[cmpTemp.char_id] = cmpTemp;
					}
				}
				WorldPacket packet;
				if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
			}
		}
		if (cmpi.char_id != 0 && cmpi.now_Channel == 0 && m_MatchStatus != enCenterMatchStatus_Pre)
		{
			WorldPacket packet;
			uint32 channelNum = GetMatchChannelNumInfo(enCenterMatchChannelStatus_using);
			std::map<uint32, uint32> temp;
			if (m_MatchMode == enCenterMatchMode_JiFenSai)
			{
				if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, cmpi.rank, cm.now_enter_num, channelNum, temp, "", enCenterMatchGameResult_LunKong))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
			}
			else if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
			{
				if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, cmpi.rank, cm.now_enter_num, channelNum, temp, "", enCenterMatchGameResult_Wait))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
			}

		}
	}
	Log.Debug("CenterMatchLogic::PlayerJoinMatch", "Char[%d] name[%s] cm_id[%d] result[%d]", pChr->getHandle(), pChr->getCharName().c_str(), m_cm_id, result);
	WorldPacket packet;
	if (sProtocolsMgr.CreateCenterMatchEnterMatchPacket(&packet, m_cm_id, m_gz_id, result))
		sGLMgr.SendProtocolsToChr(pChr, &packet);

	if (cmpi.status == enCenterMatchPlayerStatus_Free)
	{

		if (sProtocolsMgr.CreateCenterMatchWaitJoinChannelPacket(&packet, 1))
			sGLMgr.SendProtocolsToChr(pChr, &packet);


		//CheckMatchBegin();
	}
	if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	return result;
}

uint8 CenterMatchLogic::RoBotJoinMatch(CharPtr & pChr)
{
	Log.Debug("CenterMatchLogic::RoBotJoinMatch", "Char[%d] name[%s] cm_id[%d] try", pChr->getHandle(), pChr->getCharName().c_str(), m_cm_id);
	uint8 result = 0;
	if (pChr.isNull())
	{
		return result;
	}

	do
	{
		if (m_l_MatchPlayer.find(pChr->getHandle()) != m_l_MatchPlayer.end())
		{
			result = enCenterMatchJoinGameMatch_InMatch;
			break;
		}
		result = enCenterMatchResult_Sucess;
	} while (0);
	if (result == enCenterMatchResult_Sucess)
	{
		CenterMatch cm;
		sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
		if (cm.now_enter_num + 1 >= cm.enter_limit_num) return 0;
		CenterMatchPlayerInfo cmpi;
		cmpi.char_id = pChr->getHandle();
		cmpi.pid = pChr->getHandle();
		cmpi.status = enCenterMatchPlayerStatus_Free;
	
		cm.now_player++;
		cm.now_enter_num++;
		sCenterMatchMgr.UpdateCenterMatch(cm, cm.update_key);
		pChr->setStatus(CharacterStatusWar);
		pChr->setUInt32Field("status", CharacterStatusWar);
		pChr->SaveDB();
	
		if (sXmlDataMgr.getRobotShowPid(cmpi.char_id))
		{
			cmpi.pid = sXmlDataMgr.getRobotShowPid(cmpi.char_id);
			cmpi.bCenterRobot = true;
		}
		m_l_MatchPlayer.insert(std::make_pair(cmpi.char_id, cmpi));
		WorldPacket packet;
		if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}
	else if (result == enCenterMatchJoinGameMatch_InMatch)
	{
		result = enCenterMatchResult_Sucess;
	}
	Log.Debug("CenterMatchLogic::RoBotJoinMatch", "Char[%d] name[%s] cm_id[%d] pid[%d] result[%d]", pChr->getHandle(), pChr->getCharName().c_str(), m_cm_id, sXmlDataMgr.getRobotShowPid(pChr->getHandle()), result);

	return result;
}

void CenterMatchLogic::Update()
{
	//WGS_CENTERMATCHLOGIC_LOCK;
	uint32 _time = time(0);
	/*if (_time - updateTimer >= 1000)
	{
		updateTimer = _time;
	}
	else
	{
		return;
	}*/
	std::map<uint32, CenterMatchChannelInfo>::iterator iter, ei = m_l_MatchChannel.end();
	for (iter = m_l_MatchChannel.begin(); iter != ei; ++iter)
	{
		WGS_CENTERMATCHLOGIC_LOCK;
		if (iter->second.m_matchStageContinueWaitTimer && _time - iter->second.m_matchStageContinueWaitTimer >= sXmlDataMgr.GetConfXMLValue("CENTER_MATCH_STAGE_CONTINUE"))
		{
			CenterMatchChannelInfo & channelInfo = iter->second;
			iter->second.m_matchStageContinueWaitTimer = 0;
			iter->second.status = enCenterMatchChannelStatus_ended;
			std::vector<CenterMatchPlayerInfo> cmpitemp;
			for (uint8 i = 0; i < iter->second.PlayerList.size(); i++)
			{
				uint32 char_id = iter->second.PlayerList[i];
				CharPtr pChr = sCharMgr.load(char_id);
				WorldPacket packet;

			/*	if (sProtocolsMgr.CreateCenterMatchWaitJoinChannelPacket(&packet, 1))
					sGLMgr.SendProtocolsToChr(pChr, &packet);

				if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
					sGLMgr.SendProtocolsToChr(pChr, &packet);*/

				//uint32 char_id = channelInfo.PlayerList[i];
				Log.Debug("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d] char_id[%d]", channelInfo.ChannelId, char_id);
				if (m_l_MatchPlayer.find(char_id) == m_l_MatchPlayer.end()) { ASSERT(0); }
				m_l_MatchPlayer[char_id].status = enCenterMatchPlayerStatus_Free;
				m_l_MatchPlayer[char_id].now_Channel = 0;
				m_l_MatchPlayer[char_id].last_Channel = channelInfo.ChannelId;
				cmpitemp.push_back(m_l_MatchPlayer[char_id]);
			}
			//for (uint8 i = 0; i < channelInfo.PlayerList.size(); i++)
			//{//检测数据
			//	uint32 char_id = channelInfo.PlayerList[i];
			//}
			Log.Success("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d] In update", channelInfo.ChannelId);
			SendPlayerRankInfo(cmpitemp);
			

			//	m_l_MatchChannel[channel_id].status != enCenterMatchChannelStatus_ended;

			bool bAllEnd = true;

			for (std::map<uint32, CenterMatchChannelInfo >::iterator iter2 = m_l_MatchChannel.begin(); iter2 != m_l_MatchChannel.end(); iter2++)
			{
				if (iter2->second.status == enCenterMatchChannelStatus_using)
				{
					bAllEnd = false;
				}
			}
			if (bAllEnd)
			{
				m_StageLoop++;
				Log.Success("CenterMatchLogic::ChannelFinishALoop", "ChannelId[%d] Add m_StageLoop[%d]", channelInfo.ChannelId, m_StageLoop);
			}

			//处理淘汰玩家
			uint32 stageStatus = StageCheck();
			Log.Debug("CenterMatchLogic::ChannelFinishALoop", "cm_id[%d] stageStatus[%d] bAllEnd[%d]", m_cm_id, stageStatus, bAllEnd);
		//	channelInfo.m_matchStageContinueWaitTimer = time(0);

			for (uint8 i = 0; i < iter->second.PlayerList.size(); i++)
			{
				uint32 char_id = iter->second.PlayerList[i];
				CharPtr pChr = sCharMgr.load(char_id);
				WorldPacket packet;

				if (sProtocolsMgr.CreateCenterMatchWaitJoinChannelPacket(&packet, 1))
					sGLMgr.SendProtocolsToChr(pChr, &packet);

				if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
			}
			switch (stageStatus)
			{
			case enCenterMatchStage_Continue:
			{
				m_MatchStageStatus = enCenterMatchStageStatus_Continue;
				if (IsMatchPlayer())
				{
					AssignedToChannel();
					return;
				}
				
			}
			break;
			case enCenterMatchStage_WaitGameingChannel:
			{

				m_MatchStageStatus = enCenterMatchStageStatus_WaitOtherPlayer;
			}
			break;
			case enCenterMatchStage_WaitNextStage:
			{
				
				m_matchStageEndWaitTimer = time(0);
				/*if (GoToNextStage() == enCenterMatchNextStage_END)
				{
				MatchEnd();
				
				return true;
				}*/
				m_MatchStageStatus = enCenterMatchStageStatus_End;
			}

			break;
			default:
				break;
			}

		}
	}
	if (m_matchStageEndWaitTimer && _time - m_matchStageEndWaitTimer >= sXmlDataMgr.GetConfXMLValue("CENTER_MATCH_STAGE_NEXT"))
	{

		bool bAllEnd = true;
		Log.Debug("CenterMatchLogic::Update", "cm_id[%d] over", m_cm_id);
		for (std::map<uint32, CenterMatchChannelInfo >::iterator iter = m_l_MatchChannel.begin(); iter != m_l_MatchChannel.end(); iter++)
		{
			if (iter->second.status == enCenterMatchChannelStatus_using)
			{
				bAllEnd = false;
			}
		}
		//处理淘汰玩家

		if (m_MatchMode == enCenterMatchMode_TaoTaiSai && bAllEnd)
		{
			Log.Debug("CenterMatchLogic::Update", "cm_id[%d] over m_StageLoop[%d] m_CenterMatchStage.stage_loop[%d]", m_cm_id, m_StageLoop, m_CenterMatchStage.stage_loop);
			if (m_StageLoop == m_CenterMatchStage.stage_loop && m_bFinals == false)
			{
				EliminatePlayer();
				m_matchRiseUpWaitTimer = time(0);
			}
		}
		uint8 nextStage = GoToNextStage();
		Log.Debug("CenterMatchLogic::Update", "nextStage cm_id[%d] m_bFinals[%d] nextStage[%d]", m_cm_id, m_bFinals, nextStage);
		if (nextStage == enCenterMatchNextStage_END)
		{
			MatchEnd();
			if (m_bFinals)
			{
				GiveMatchPrize();
			}

			Log.Success("CenterMatchLogic::Update", "cm_id[%d] enCenterMatchOverType_GoodEnd", m_cm_id, m_bFinals, nextStage);
		//	sCenterMatchMgr.CenterMatchOver(m_cm_id, enCenterMatchOverType_GoodEnd);

			m_MatchStageStatus = enCenterMatchStageStatus_GameEnd;
			return;
		}
		else
		{
			if (IsMatchPlayer() && m_matchRiseUpWaitTimer == 0)
			{
			//	WGS_CENTERMATCHLOGIC_LOCK;

				Log.Debug("CenterMatchLogic::Update", "cm_id[%d] MatchPlayer m_bFinals[%d] nextStage[%d]",m_cm_id, m_bFinals, nextStage);
				AssignedToChannel();
			}
		}
		m_matchStageEndWaitTimer = 0;

	}
	if (m_matchRiseUpWaitTimer != 0 && _time - m_matchRiseUpWaitTimer >= sXmlDataMgr.GetConfXMLValue("CENTER_MATCH_STAGE_CONTINUE"))
	{
		m_matchRiseUpWaitTimer = 0;
		if (IsMatchPlayer())
		{
			Log.Debug("CenterMatchLogic::Update", "cm_id[%d] Rise Up MatchPlayer ", m_cm_id);
			AssignedToChannel();
		}
	}
	if (m_MatchMode == enCenterMatchMode_JiFenSai &&  m_matchStartWaitTimer != 0 && m_CenterMatchStage.limit_time != 0 && _time - m_matchStartWaitTimer >= m_CenterMatchStage.limit_time * 60)
	{
		m_MatchStageStatus = enCenterMatchStageStatus_WaitOtherPlayer;
	}

	if (m_MatchStatus == enCenterMatchStatus_Pre)
	{
		Robot();
		return;
	}

	//淘汰分数成长
	//UpdateEliminate();

}

//淘汰分数成长
void CenterMatchLogic::UpdateEliminate()
{
	if (m_CenterMatchStage.stageMode == enCenterMatchRuleMode_DaLiChuJu)
	{
		uint32 __time = time(0);
		uint32 passTime = __time - m_MatchBeginTime;
		uint32 _addTime = 0;
		for (uint32 i = 0; i < m_CenterMatchStage.EliminateIncrease.size(); i++)
		{
			_addTime += m_CenterMatchStage.EliminateIncrease[i].timeUp;
			if (_addTime > passTime)
			{
				if (i != 0)
				{
					if (m_CenterMatchStage.eliminate < m_CenterMatchStage.EliminateIncrease[i].eliminate)
					{
						m_CenterMatchStage.eliminate = m_CenterMatchStage.EliminateIncrease[i].eliminate;
					}
					if (m_CenterMatchStage.base_score < m_CenterMatchStage.EliminateIncrease[i].base)
					{
						m_CenterMatchStage.base_score = m_CenterMatchStage.EliminateIncrease[i].base;
					}
				}
				break;
			}
		}
	}

}

//检测比赛是否开始
bool CenterMatchLogic::CheckMatchBegin()
{
	MatchStartWait();
	//	if (m_MatchMode == enCenterMatchMode_TaoTaiSai)
	{//快速赛
		//查询报名成功人数
		std::list<CenterMatchPlayer> PlayerList;
		sCenterMatchPlayerMgr.GetCenterMatchPlayerList(&PlayerList, "cm_id = %u and status = %u and enter_status = %u", m_cm_id, 1, enCenterMatchEnterStatus_Passed);

		/*if (PlayerList.size() < m_NextRoundNum)
		{
			return false;
		}*/
		Log.Debug("CenterMatchLogic::CheckMatchBegin", "cm_id[%d] PlayerList[%d]",m_cm_id, PlayerList.size());
		for (std::list<CenterMatchPlayer>::iterator iter = PlayerList.begin(); iter != PlayerList.end(); iter++)
		{
			std::list<UserPtr>  UserList;
			sUserMgr.getUserList(&UserList, 0, 1, "gz_id = %d and platform_id = %d", m_gz_id, iter->pid);
			Log.Debug("CenterMatchLogic::CheckMatchBegin", "UserList[%d] gz_id[%d] pid[%d]", UserList.size(), iter->gz_id, iter->pid);



			if (UserList.empty()) continue;

			UserPtr pUser = *UserList.begin();

			CharPtr pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));

			if (pChr.isNull() == false)
			{
				pChr->setStatus(CharacterStatusWar);
				pChr->setUInt32Field("status", CharacterStatusWar);
				pChr->SaveDB();
			}

			PlayerJoinMatch(pUser);
		}
		CenterMatch cm;
		sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
		if (m_l_MatchPlayer.size() > cm.enter_limit_num)
		{
			ReduceRobot(m_l_MatchPlayer.size() - cm.enter_limit_num );
		}
		CMPIter iter, ei = m_l_MatchPlayer.end();
	
		for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
		{
			if (iter->second.bCenterRobot == true)
			{
				Log.Debug("CenterMatchLogic::CheckMatchBegin", "cm_id[%d] Add Robot Log pid[%d]", m_cm_id, iter->second.pid);
				CenterMatchPlayer temp;
				CharPtr pChr = sCharMgr.load(iter->second.char_id);
				temp.battle_name = cm.battle_name;
				temp.create_time = sGLMgr.GetCurDateTime();
				temp.end_time = String("");
				temp.fz_pid = cm.pid;
				temp.cm_id = cm.cm_id;
				temp.reg_from = cm.reg_from;
				temp.game_id = cm.game_id;
				temp.group_id = cm.group_id;
				temp.gz_id = cm.gz_id;
				temp.head = pChr->getStringField("desc");
				temp.join_code = cm.join_code;
				temp.match_status = cm.match_status;
				temp.enter_status = enCenterMatchEnterStatus_Passed;
				temp.name = pChr->getStringField("name");
				temp.openid = cm.openid;
				temp.pid = iter->second.pid;
				temp.player_gz_id = 0;
				temp.status = 1;
				sCenterMatchPlayerMgr.AddCenterMatchPlayer(temp);
			}
		}
		UpdateCenterMatchPlayerRank();

		GoToNextStage();

		AssignedToChannel();

		m_MatchStatus = enCenterMatchStatus_Gaming;
	}
	//else if (m_MatchMode == enCenterMatchMode_JiFenSai)
	//{//时长赛
	//	//立即开始
	//	m_MatchStatus = enCenterMatchStatus_Gaming;
	//}
	//else
	//{
	//	Log.Error("CenterMatchLogic::CheckMatchBegin", "cm_id:%u  m_MatchMode:%u", m_cm_id, m_MatchMode);
	//	return false;
	//}
	return true;
}

//开启比赛开始倒计时
void CenterMatchLogic::MatchStartWait()
{
	WGS_CENTERMATCHLOGIC_LOCK;
	m_robotLeaveTimer = 0;
	m_matchStartWaitTimer = time(0);
}

//发送比赛奖品
void CenterMatchLogic::GiveMatchPrize()
{
	CenterMatch cm;
	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata2, val);
	if (val.isMember("prize"))
	{
		Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] val[\"prize\"].size[%d]", m_cm_id, val["prize"].size());
	//	if (val["prize"].size() != 0)
		{
			std::vector<std::map<uint32, uint32> > prizeList;
			for (uint32 i = 0; i < val["prize"].size(); i++)
			{
				String ranklist = val["prize"][i]["ranklist"].asString();
				std::vector<String> vStr = StringUtil::split(ranklist, ",");
				uint32 _first = StringConverter::parseInt(vStr.front());
				uint32 _scend = StringConverter::parseInt(vStr.back());
				Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] _first[%d] _scend[%d]", m_cm_id, _first, _scend);

				for (uint32 r = _first; r <= _scend; r++)
				{
					std::map<uint32, uint32> temp;
					for (uint32 item = 0; item < val["prize"][i]["items"].size(); item++)
					{
						uint32 msId = val["prize"][i]["items"][item]["msId"].asUInt();
						uint32 num = val["prize"][i]["items"][item]["num"].asUInt();
						Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] msId[%d] num[%d]", m_cm_id, msId, num);
						if (msId && num)
						{
							temp[msId] = num;
						}
					}
					prizeList.push_back(temp);
				}
			}
			std::list<CenterMatchPlayer> MatchPlyaerList;
			sCenterMatchPlayerMgr.GetCenterMatchPlayerList(&MatchPlyaerList, "cm_id = %d and enter_status = %d and sdata1 <> '%d' order by data2",m_cm_id, enCenterMatchEnterStatus_Passed,enCenterMatchPlayerStatus_Eliminate);
			std::list<CenterMatchPlayer>::iterator iterPlayer, eiPlayer = MatchPlyaerList.end();
			uint32 _index = 0;
			Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] MatchPlyaerList[%d] prizeList[%d]", m_cm_id, MatchPlyaerList.size(), prizeList.size());
			Json::Value  winners ;
			for (iterPlayer = MatchPlyaerList.begin(); iterPlayer != eiPlayer; ++iterPlayer)
			{
				if (_index > MatchPlyaerList.size() - 1) break;
				CharPtr pChr;
				std::list<UserPtr> UserList;
				sUserMgr.getUserList(&UserList, 0, 1, "platform_id = %d and gz_id = %d", iterPlayer->pid, iterPlayer->gz_id);
				if (UserList.size())
				{
					UserPtr pUser = *UserList.begin();
					pChr = sCharMgr.load(pUser->getUInt32Field("char_id"));
				}
				String prizeString = "";
				if (_index + 1> prizeList.size() || pChr.isNull())
				{
					WorldPacket packet;
					std::map<uint32, uint32> prizeTemp;
					uint8 result = enCenterMatchGameResult_Win;
					if(m_MatchMode == enCenterMatchMode_JiFenSai)
						result = enCenterMatchGameResult_Win;

					Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] now_rank[%d] now_playerNum[%d] now_channel[%d] prizeTemp[%d] prizeString[%s] result[%d]", m_cm_id, iterPlayer->data2, cm.now_enter_num,0, prizeTemp.size(), prizeString.c_str(), result);
					if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iterPlayer->data2, cm.now_enter_num,0, prizeTemp, prizeString, result))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					_index++;
					continue;
				}
				
				std::map<uint32, uint32> prizeTemp = prizeList[_index];
				std::map<uint32, uint32>::iterator iterPrize, itprizeTemp, eiPrize = prizeTemp.end();
				Json::Value temp;
				temp["head"] = pChr->getStringField("desc");
				temp["name"] = pChr->getStringField("name");
				temp["pid"] = iterPlayer->pid;
				temp["score"] = iterPlayer->data4;
				winners.append(temp);

				
				for (iterPrize = prizeTemp.begin(); iterPrize != eiPrize; ++iterPrize)
				{
					String item_name = sXmlDataMgr.GetItemModelNameByAgentID(m_agent_id, iterPrize->first);
					prizeString += item_name + "x" + StringConverter::toString(iterPrize->second);
					itprizeTemp = iterPrize;
					if (++itprizeTemp != eiPrize)
						prizeString += "、";
					Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] pChr[%d] _index[%d] msId[%d] num[%d]", m_cm_id, pChr->getHandle(), _index, iterPrize->first, iterPrize->second);
					sGLMgr.addItemNum(pChr, iterPrize->first, iterPrize->second);
				}
				/*if (iterPrize == eiPrize)
				{
					if (prizeString.size() >= 2)
					{
						prizeString = prizeString.substr(0, prizeString.size() - 2);
					}
				}*/
				WorldPacket packet;
				Log.Debug("CenterMatchLogic::GiveMatchPrize", "cm_id[%d] now_rank[%d] now_playerNum[%d] now_channel[%d] prizeTemp[%d] prizeString[%s] enCenterMatchGameResult_Win", m_cm_id, iterPlayer->data2, cm.now_enter_num, 0, prizeTemp.size(), prizeString.c_str());
				if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iterPlayer->data2, cm.now_enter_num,0, prizeTemp, prizeString, enCenterMatchGameResult_Win))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				_index++;
			}
			if (cm.cm_id != 0)
			{
			/*	sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
				cm.sdata3 = Json::FastWriter().write(winners);
				sCenterMatchMgr.UpdateCenterMatch(cm, cm.update_key);*/
			}
		}
	}

	
}

//获取牌桌列表
std::vector<uint32> CenterMatchLogic::GetChannelIdList()
{
	std::vector<uint32> ChannelIdList;
	for (std::map<uint32,CenterMatchChannelInfo>::iterator iter = m_l_MatchChannel.begin(); iter != m_l_MatchChannel.end(); iter++)
	{
		if (iter->second.status == enCenterMatchChannelStatus_using)
		{
			ChannelIdList.push_back(iter->second.ChannelId);
		}
	}
	return ChannelIdList;
}

//玩家离开比赛
void CenterMatchLogic::PlayerLeaveGameMatch(CharPtr pChr)
{

	Log.Debug("CenterMatchLogic::PlayerLeaveGameMatch", "cm_id[%d] pChr[%d]", m_cm_id, pChr->getHandle());
	if (m_l_MatchPlayer.find(pChr->getHandle()) != m_l_MatchPlayer.end())
	{
		m_l_MatchPlayer.erase(m_l_MatchPlayer.find(pChr->getHandle()));
		CMPIter iter, ei = m_l_MatchPlayer.end();
		for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
		{
			CharPtr pChrInMatch = sCharMgr.getByHandle(iter->second.char_id);
			if (pChrInMatch.isNull() == false)
			{
				WorldPacket packet;
				if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
					sGLMgr.SendProtocolsToChr(pChrInMatch, &packet);
			}
		}
		Log.Debug("CenterMatchLogic::PlayerLeaveGameMatch", "cm_id[%d] m_l_MatchPlayer  earse pChr[%d]", m_cm_id, pChr->getHandle());
	}
	if (m_vWatchList.find(pChr->getHandle()) != m_vWatchList.end())
	{
		m_vWatchList.erase(m_vWatchList.find( pChr->getHandle()));
		Log.Debug("CenterMatchLogic::PlayerLeaveGameMatch", "cm_id[%d] m_vWatchList  earse pChr[%d]", m_cm_id, pChr->getHandle());
	}
}

//玩家观战
void CenterMatchLogic::PlayerWatchMatch(CharPtr pChr, const uint32 & channelId)
{
	std::map<uint32,uint32>::iterator findIter = m_vWatchList.find(pChr->getHandle());
	if (findIter == m_vWatchList.end())
	{
		if (m_l_MatchChannel.find(channelId) != m_l_MatchChannel.end())
		{
			CenterMatchChannelInfo & cmci = m_l_MatchChannel.find(channelId)->second;
			m_vWatchList[pChr->getHandle()] = cmci.ChannelId;
			cmci.WatchPlayerList.push_back(pChr->getHandle());
			/*std::map<uint32, CenterMatchPlayerInfo> temp;
			CenterMatch cm;
			sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
			for (uint32 i = 0; i < cmci.PlayerList.size(); i++)
			{
				if (m_l_MatchPlayer.find(cmci.PlayerList[i]) != m_l_MatchPlayer.end())
				{
					CenterMatchPlayerInfo cmpi = m_l_MatchPlayer.find(cmci.PlayerList[i])->second;
					temp[cmpi.char_id] = cmpi;
				}
			}
			WorldPacket packet;
			if (sProtocolsMgr.CreateCenterMatchStageInofPacket(&packet, this))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
			if (sProtocolsMgr.CreateCenterMatchPlayerInfoListInCenterPacket(&packet, pChr, cm, temp))
				sGLMgr.SendProtocolsToChr(pChr, &packet);*/

		}
	
	}
}

//通知玩家更新排名
void CenterMatchLogic::SendPlayerRankInfo()
{
	WGS_CENTERMATCHLOGIC_LOCK;
	if (m_MatchMode != enCenterMatchMode_TaoTaiSai && m_MatchStageStatus != enCenterMatchStageStatus_WaitOtherPlayer) return;
	CMPIter iter, ei = m_l_MatchPlayer.end();
	uint32 nowPlayerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) + GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_InChannel);
	uint32 nowChannels = GetMatchChannelNumInfo(enCenterMatchChannelStatus_using);
	WorldPacket packet;
	for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
	{
		if (iter->second.status != enCenterMatchPlayerStatus_Free) continue;
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		uint8 reuslt = enCenterMatchGameResult_Wait;
		if (m_MatchMode == enCenterMatchMode_JiFenSai)
		{
			reuslt = enCenterMatchGameResult_LunKong;
		}
		if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, iter->second.rank, nowPlayerNum, nowChannels, std::map<uint32, uint32>(), "", reuslt))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}

}

void CenterMatchLogic::SendPlayerRankInfo(std::vector<CenterMatchPlayerInfo> temp)
{
	if (m_MatchMode != enCenterMatchMode_TaoTaiSai && m_MatchStageStatus != enCenterMatchStageStatus_WaitOtherPlayer) return;
	uint32 nowPlayerNum = GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_Free) + GetMatchPlayerNumInfo(enCenterMatchPlayerStatus_InChannel);
	uint32 nowChannels = GetMatchChannelNumInfo(enCenterMatchChannelStatus_using);
	WorldPacket packet;
	for (uint32 i = 0; i < temp.size(); i++)
	{
		CharPtr pChr = sCharMgr.load(temp[i].char_id);
		uint8 reuslt = enCenterMatchGameResult_Wait;
		if (m_MatchMode == enCenterMatchMode_JiFenSai)
		{
			reuslt = enCenterMatchGameResult_LunKong;
		}
		if (sProtocolsMgr.CreateCenterMatchRiseOrDownNotifyPacket(&packet, temp[i].rank, nowPlayerNum, nowChannels, std::map<uint32, uint32>(), "", reuslt))
			sGLMgr.SendProtocolsToChr(pChr, &packet);
	}
}

//机器的去与留
void CenterMatchLogic::Robot()
{
	WGS_CENTERMATCHLOGIC_LOCK;
	if (m_robotLeaveTimer == 0)
		return;
	uint32 _time = time(0);
	if (_time > m_robotLeaveTimer)
	{
		CenterMatch cm;
		sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
		if (cm.b_enter == false) return;
		if (cm.cm_id == 0) return;
		Json::Value val;
		Json::Reader reader;
		reader.parse(cm.sdata2, val);

		int num = 0;
		if (val.isMember("robotnum"))
			num = val["robotnum"].asInt();

		int now_robot = GetRobotNum();
		Log.Debug("CenterMatchLogic::Robot", "cm_id[%d] num[%d] now[%d]", m_cm_id, num, now_robot);


		if (num == 0)
		{
			ReduceRobot(now_robot);
		}
		else if (now_robot < num)
		{
			int RandomChange = RandomUInt(0, num - now_robot);
			if (RandomChange + cm.now_enter_num >= cm.enter_limit_num)
				RandomChange = 0;
			AddRobot(RandomChange);
		}
		else
		{
			int RandomChange = RandomUInt(1, now_robot - num);
			if (RandomChange + m_l_MatchPlayer.size() >= cm.enter_limit_num)
			{
				if (m_l_MatchPlayer.size() >= cm.enter_limit_num)
				{
					return;
				}
				else
				{ 
					RandomChange = cm.enter_limit_num - m_l_MatchPlayer.size() - 1;

				}
			}
			ReduceRobot(RandomChange);
		}


		m_robotLeaveTimer = time(0) + RandomUInt(5, 15);
	}
}

//获取机器人数量
int CenterMatchLogic::GetRobotNum()
{
	int num = 0;
	CMPIter iter, ei = m_l_MatchPlayer.end();
	for (iter = m_l_MatchPlayer.begin(); iter != ei; ++iter)
	{
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		if (pChr.isNull()) continue;
		if (pChr->isNPC() || sXmlDataMgr.IsBankerInContrlList(iter->second.char_id))
			num++;
		/*if (iter->second.bCenterRobot == true)
			num++;
		*/
	}
	return num;
}

bool CenterMatchLogic::AddRobot(int num)
{
	for (int i = 0; i < num; i++)
	{
		uint32 charId = sXmlDataMgr.getBankerInContrlCharIdRandom();
		CharPtr chr;
		if (charId != 0)
		{
			chr = sCharMgr.load(charId);
		}
		if (chr.isNull())
		{
			Resource * pChar = sCharMgr.newDumyChar();

			if (!pChar)
			{
				Log.Debug("CenterMatchLogic::AddRobot", "newDumyChar NULL");
				return false;
			}
			Vector3 pos = sRegionMgr.getWorldRondomPosition();
			pChar->setFloatField("x", pos.x);
			pChar->setFloatField("y", pos.y);
			pChar->setUInt32Field("id", RandomUInt(511, 513));
			uint32 number = (RandomUInt(10032, 20001));
			String name = "御坂" + StringConverter::toString(number);
			if (number == 20001)
				name = "最后之作";
			if (!StringUtil::checkStringUTF8(name))
				name = StringUtil::StringToUTF8(name);
			pChar->setStringField("name", name);
			pChar->setUInt32Field("lv", 1);
			pChar->setUInt32Field("exps", 0);
			pChar->setUInt32Field("status", CharacterStatusFree);
			pChar->setUInt32Field("create_time", time(0));
			pChar->setUInt32Field("isnpc", 2);
			pChar->setUInt32Field("motion", i);														//总场次
			pChar->setUInt32Field("payment", 0);														//胜场
			pChar->setUInt32Field("attribute", 0);																//跪场
			pChar->setUInt32Field("ability", 0);														//胜率
			pChar->setUInt32Field("defence_ext", 0);													//击坠
			pChar->setUInt32Field("attack_ext", 0);													//勋章
			pChar->setUInt32Field("hp", 1);															//勋章等级
			pChar->setUInt32Field("protect", 1);														//经验
			pChar->setUInt32Field("max_hp", 0);														//遥控骰子	
			pChar->setUInt32Field("speed", 500000);
			pChar->setStringField("desc", "http://192.168.0.165/gwmember/kefu/128x128.png");
			//		pChar->setStringField("desc", "	file://192.168.0.173/zm/a.png");

			chr = sCharMgr.loadCharDatabase(pChar);
			sCharMgr.freeDumyChar(pChar);
		}


		
		uint8 result = RoBotJoinMatch(chr);
		if (charId != 0 && result)
		{
			sXmlDataMgr.setRobotUsed(charId, true);
			m_l_MatchPlayer[charId].bCenterRobot = true;
		}
	}
	
	return true;
}

//减少机器人
bool CenterMatchLogic::ReduceRobot(int num)
{
	if (num == 0)
		return true;
	int now_robot = GetRobotNum();
	if (num > now_robot)
		num = now_robot;
	CMPIter iter, ei = m_l_MatchPlayer.end();
	for (iter = m_l_MatchPlayer.begin(); iter != ei;)
	{
	//	if (iter->second.bCenterRobot)
		CharPtr pChr = sCharMgr.load(iter->second.char_id);
		if(pChr.isNull() == false && (pChr->isNPC() || sXmlDataMgr.IsBankerInContrlList(iter->second.char_id)) )
		{
			sXmlDataMgr.setRobotUsed(iter->second.char_id, false);
			m_l_MatchPlayer.erase(iter++);
			CenterMatch cm;
			sCenterMatchMgr.GetCenterMatch(m_cm_id, &cm);
			if (cm.now_enter_num > 0)
				cm.now_enter_num--;
			sCenterMatchMgr.UpdateCenterMatch(cm, cm.update_key);
			if (--num == 0)
				break;
			continue;
		}
		++iter;
	}

	return true;
}

